在Python中通过Exchange服务器发送邮件,通常借助exchangelib库对接Exchange Web Services(EWS)。该方式比SMTP更适配企业环境,能直接使用域账号身份发信。

环境准备
首先安装exchangelib库,建议使用虚拟环境隔离依赖:
pip install exchangelib
连接Exchange服务器
使用Credentials存放账号密码,通过Account对象指定主SMTP地址与EWS终端。若企业使用自动发现,可设autodiscover为True。
基础连接示例
from exchangelib import Credentials, Account, Configuration
# 填写自己的域账号与密码
creds = Credentials(username='domain\user', password='your_password')
# 若关闭自动发现,手动指定EWS地址
config = Configuration(server='mail.ipipp.com', credentials=creds)
account = Account(
primary_smtp_address='user@ipipp.com',
config=config,
autodiscover=False
)
print(account.protocol.server)构造并发送邮件
邮件由Message对象表示,设置收件人、主题、正文后调用send方法即可。正文支持纯文本与HTML。
发送纯文本邮件
from exchangelib import Message, Mailbox
msg = Message(
account=account,
subject='Python自动通知',
body='这是一封由Python通过Exchange发送的测试邮件。',
to_recipients=[Mailbox(email_address='receiver@ipipp.com')]
)
msg.send()发送带HTML与附件的邮件
from exchangelib import Message, Mailbox, FileAttachment
html_body = '<h1>报表</h1><p>请查收今日数据。</p>'
msg = Message(
account=account,
subject='每日报表',
body=html_body,
to_recipients=[Mailbox(email_address='receiver@ipipp.com')]
)
# 添加本地文件作为附件
with open('report.csv', 'rb') as f:
msg.attachments.append(
FileAttachment(name='report.csv', content=f.read())
)
msg.send()常见注意事项
- 账号需有EWS访问权限,部分企业会限制第三方客户端。
- 密码若含特殊字符,注意转义或使用环境变量存储。
- 大量发送时建议复用Account对象,避免频繁建连。
使用Exchange发邮件能与企业通讯录、日历打通,适合内部系统通知场景。
小结
通过exchangelib库,Python可简洁地完成Exchange发信。掌握Credentials、Account与Message的用法后,便能轻松将邮件能力嵌入运维或业务脚本中。
PythonExchangesend_email修改时间:2026-07-29 13:54:22