使用Python发送带附件的邮件应该怎么做?
时间: 2024-09-24 11:29:33 浏览: 82
Python基于SMTP协议实现发送邮件功能详解
5星 · 资源好评率100%
在Python中,如果你想发送带有附件的邮件,可以在MIMEText对象的基础上创建一个MIMEBase对象来代表附件。以下是一个示例,展示了如何发送带文本和附件的电子邮件:
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from os.path import basename
# ... (之前配置发件人、收件人和密码)
# 创建主邮件部分
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = '带有附件的邮件'
# 添加纯文本内容
text = '这是邮件正文...'
msg.attach(MIMEText(text, 'plain'))
# 附加文件
with open('path_to_your_attachment', 'rb') as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part) # 对二进制数据进行编码
part.add_header('Content-Disposition', f'attachment; filename="{basename(attachment.name)}"')
msg.attach(part)
# ... (之后连接到SMTP服务器和发送邮件)
阅读全文