python 发送带附件的邮件
时间: 2023-09-28 13:04:12 浏览: 92
python发送带附件的邮件
发送带附件的邮件可以使用 Python 标准库中的 `email` 和 `smtplib` 模块。下面是一个示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
sender_email = 'sender@example.com'
sender_password = 'password'
receiver_email = 'receiver@example.com'
# 创建一个带附件的邮件对象
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = '测试邮件'
# 邮件正文
text = '这是一封带附件的邮件'
message.attach(MIMEText(text))
# 附件
filename = 'test.txt'
with open(filename, 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(attachment)
# 发送邮件
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, message.as_string())
```
在上面的代码中,我们首先创建一个 `MIMEMultipart` 对象作为邮件容器,然后分别设置邮件的发送者、接收者和主题。接着添加邮件正文和附件,最后通过 SMTP 服务器发送邮件。需要注意的是,如果你要发送带附件的邮件,SMTP 服务器需要支持 STARTTLS 协议以加密邮件传输。
阅读全文