使用exchangelib库可实现Python通过Exchange服务器发送邮件。1. 安装库:pip install exchangelib;2. 配置账号信息并创建Account对象,支持自动发现服务器;3. 构造Message对象发送基础邮件;4. 通过FileAttachment添加文件附件;5. 注意网络访问、认证方式及发送频率。

Python中通过Exchange服务器发送邮件,通常使用 exchangelib 库,它是专为与Microsoft Exchange Server交互设计的开源库,支持现代认证方式(如OAuth、NTLM等),适用于Office 365和本地Exchange服务。
在使用前先安装依赖库:
<code>pip install exchangelib
需要提供邮箱账号、密码以及服务器信息。以下是一个基本示例:
立即学习“Python免费学习笔记(深入)”;
<pre class="brush:php;toolbar:false;">from exchangelib import Account, Credentials, Message, Mailbox <h1>账号认证信息</h1><p>credentials = Credentials( username='your_email@company.com', # 完整邮箱地址 password='your_password' )</p><h1>创建账户对象,自动检测服务器配置</h1><p>account = Account( primary_smtp_address='your_email@company.com', credentials=credentials, autodiscover=True, # 自动发现Exchange服务器 access_type='delegate' # 可选:delegate 或 impersonation )</p>
构造并发送一封基础邮件:
<pre class="brush:php;toolbar:false;"># 创建邮件对象
msg = Message(
account=account,
subject='测试邮件',
body='这是一封通过Python发送的测试邮件。',
to_recipients=[
Mailbox(email_address='recipient@example.com')
]
)
<h1>发送</h1><p>msg.send()
print("邮件已发送")</p>如果需要添加文件附件:
<pre class="brush:php;toolbar:false;">from exchangelib import FileAttachment
<h1>创建消息</h1><p>msg = Message(
account=account,
subject='带附件的邮件',
body='请查收附件。',
to_recipients=[Mailbox(email_address='user@domain.com')]
)</p><h1>添加附件</h1><p>with open('example.pdf', 'rb') as f:
file_attachment = FileAttachment(
name='report.pdf',
content=f.read()
)
msg.attach(file_attachment)</p><p>msg.send()
print("带附件的邮件已发送")</p>基本上就这些。只要账号权限正确,exchangelib 使用起来稳定且直观。
以上就是Python中Exchange发邮件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号