python发送、接收exchange邮件

导包

import datetime
from pathlib import Path

import pytz
from exchangelib import (
    Configuration, Account, DELEGATE, Q,
    Credentials, HTMLBody, Message, FileAttachment
)
from exchangelib.protocol import CachingProtocol

连接邮箱

server = 'example.com'  # 邮箱服务器地址
domain = 'domain.example.com'  # 域名
username = 'your_username'  # 用户名
password = 'your_password'  # 密码
address = 'your_email_address'  # 邮箱地址


def outlook_login():
    """
    连接Outlook邮箱
    :return: 邮箱对象
    """
    try:
        # 账户信息(域用户)
        config = Configuration(
            server=server,
            credentials=Credentials(f'{domain}\{username}', password)
        )
        # 连接邮箱账号
        account = Account(
            primary_smtp_address=address,
            config=config,
            autodiscover=False,
            access_type=DELEGATE
        )
        return account
    except Exception as e:
        print(f'邮箱连接失败,原因:{str(e)}')
        CachingProtocol.clear_cache()
        return

接收邮件

def received_outlook_message():
    """
    接收Exchange邮件
    return:邮件对象集合
    """
    account = outlook_login()
    if not account:
        print('outlook登录失败')
        return []
    
    sub1 = 'Indicative Deposit Rates'
    sub2 = 'Time Deposit Indication'
    # 设置时区
    tz = pytz.timezone('Asia/Shanghai')
    today = datetime.datetime.now(tz).date()

    # 时间过滤:当天
    start_of_day = tz.localize(datetime.datetime.combine(today, datetime.datetime.min.time()))
    end_of_day = tz.localize(datetime.datetime.combine(today, datetime.datetime.max.time()))

    # 主题过滤
    sub_filter = (Q(subject__icontains=sub1) | Q(subject__icontains=sub2))

    # 组合过滤条件
    mail_filter = Q(is_read=False) & Q(datetime_received__lte=end_of_day) & Q(
        datetime_received__gte=start_of_day) & sub_filter

    # 读取符合条件的邮件
    unread_message = account.inbox.filter(mail_filter)
    return unread_message

发送邮件

def send_outlook_mail(subject, body, to_email, cc_email=None, bcc_email=None, attachments=None):
    """
    发送邮件
    :param subject: 邮件主题
    :param body: 邮件正文
    :param to_email: 收件人
    :param cc_email: 抄送人
    :param bcc_email: 密送人
    :param attachments: 附件列表
    :return:
    """
    account = outlook_login()
    if not account:
        print('outlook登录失败')
        return
    mail = Message(
        account=account,
        folder=account.sent,
    )
    mail.subject = subject
    mail.body = HTMLBody(body)
    if isinstance(to_email, str):
        to_email = [to_email]
    mail.to_recipients = to_email
    if isinstance(cc_email, str):
        cc_email = [cc_email]
    mail.cc_recipients = cc_email
    if isinstance(bcc_email, str):
        bcc_email = [bcc_email]
    mail.bcc_recipients = bcc_email
    if attachments:
        for attachment in attachments:
            file_name = str(Path(attachment).name)
            with open(attachment, 'rb') as f:
                content = f.read()
            file = FileAttachment(name=file_name, content=content)
            mail.attach(file)
    try:
        mail.send_and_save()
    except Exception as e:
        print(f'邮件发送失败:{e}')
© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...