반응형
Python을 사용하여 Outlook 이메일을 역순으로 검토하는 방법
Outlook 전자 메일과 읽지 않은 전자 메일만 읽으려고 합니다. 제가 지금 가지고 있는 코드는 다음과 같다:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetFirst ()
while message:
if message.Unread == True:
print (message.body)
message = messages.GetNext ()
하지만 이것은 첫번째 이메일에서 마지막 이메일로 넘어갑니다. 읽지 않은 메일이 맨 위에 있기 때문에 역순으로 가고 싶습니다. 그렇게 할 수 있는 방법이 있나요?
for 루프를 사용하면 어떨까요? 처음부터 끝까지 메시지를 마치려고 하는 것처럼 보여요.
for message in messages:
if message.Unread == True:
print (message.body)
나는 포 루프가 그들 모두를 통과하는 데 좋다는 콜의 말에 동의한다. 가장 최근에 수신한 전자 메일에서 시작하는 것이 중요한 경우(예: 특정 주문 또는 전자 메일 수 제한) 이 기능을 사용하여 속성별로 정렬할 수 있습니다.
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
#the Sort function will sort your messages by their ReceivedTime property, from the most recently received to the oldest.
#If you use False instead of True, it will sort in the opposite direction: ascending order, from the oldest to the most recent.
messages.Sort("[ReceivedTime]", True)
for message in messages:
if message.Unread == True:
print (message.body)
조금 오래된 질문이지만 이것은 이 질문에 대한 구글의 최고 게시물 중 하나이기 때문에 저는 제 경험을 추가하고 싶습니다.
메시지를 통해 반복할 때 for 루프를 사용하는 것은 코드를 구성하는 더 "파이토닉" 방식이지만, 내 경험에 따르면 프로그램이 반복되는 동안 이메일이 다른 폴더로 이동되는 등의 외부 변경으로 인해 이 특정 라이브러리/API에서 오류가 발생하는 경우가 많다.
또한 전자 메일이 아닌 경우(예: 회의 초대) 예상치 못한 결과/예외가 발생할 수 있습니다.
그러므로 나는 원래 포스터의 코드, 벡스 웨이의 수락된 답변, 그리고 나 자신의 발견을 망라한 코드를 사용한다:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
message = messages.GetFirst ()
while message:
if message.Class != 43: #Not an email - ignore it
message = messages.GetNext ()
elif message.Unread == True:
print (message.body)
message = messages.GetNext ()
반응형
'개발하자' 카테고리의 다른 글
(DRIVER_NOT_Found', "'Teradata'용 드라이버를 찾을 수 없습니다. 사용 가능한 드라이버:) - 테라데이터 모듈이 있는 아나콘다-주피터 노트북 사용 (0) | 2023.06.29 |
---|---|
파이썬에서 한 줄에 여러 개의 'with' 문이 중첩된 'with' 문과 같은가요? (0) | 2023.06.28 |
쿠베르네테스의 HPA와 ReplicaSet는 어떤 관계인가요? (0) | 2023.06.27 |
잘못된 for_each 인수로 테라폼 실패 / 지정된 "for_each" 인수 값이 적합하지 않습니다 (0) | 2023.06.27 |
클러스터 IP 서비스가 있고 기본 nginx가 있는 kubernetes 수신 컨트롤러가 예상대로 작동하지 않음 (0) | 2023.06.26 |