import os
from datetime import datetime
import pytz
from exchangelib import Credentials, Account, Configuration, DELEGATE, Q, FileAttachment
def received_exchange_message():
"""
接收exchange邮件,保存邮件到本地
:return:
"""
# 创建连接
config = Configuration(
server='exchange.example.com', # Exchange Web Services URL
credentials=Credentials('域名\\username', 'password')
)
account = Account(
primary_smtp_address='[email protected]',
config=config,
autodiscover=False,
access_type=DELEGATE
)
# 设置时区
# tz = EWSTimeZone('Asia/Shanghai')
tz = pytz.timezone('Asia/Shanghai')
# 过滤收件箱中当天未读邮件,并按照多个主题过滤
today = datetime.now(tz).date()
start_of_day = tz.localize(datetime.combine(today, datetime.min.time()))
end_of_day = tz.localize(datetime.combine(today, datetime.max.time()))
subject_filter_1 = Q(subject__icontains='主题1')
subject_filter_2 = Q(subject__icontains='主题2')
unread_filter = Q(is_read=False) & Q(datetime_received__lte=end_of_day) & Q(datetime_received__gte=start_of_day) & (
subject_filter_1 | subject_filter_2)
unread_messages = account.inbox.filter(unread_filter)
save_path = 'C:\\attachments\\'
for message in unread_messages:
print(message.subject)
print(message.sender.email_address)
print(message.datetime_received.astimezone())
print(message.body)
for attachment in message.attachments:
if isinstance(attachment, FileAttachment):
# attachment.download(save_path)
# attachment.content_location
# print(f"Attachment saved: {os.path.join(save_path, attachment.name)}")
file_path = os.path.join(save_path, attachment.name)
with open(file_path, 'wb') as f:
f.write(attachment.content)
print(f"Attachment saved: {file_path}")
# 将邮件设置为已读
message.is_read = True
message.save()
print(f"Marked as read: {message.subject}")
# 保存邮件到本地,eml格式
for email in unread_messages:
# 注意保存时的主题特殊字符等情况的替换,否则会保存失败
with open(f'{email.subject}.eml', 'wb') as f:
f.write(email.mime_content)
标签:exchange,python,datetime,filter,exchangelib,print,path,message,subject
From: https://www.cnblogs.com/rong-z/p/17414923.html