python中sendmail发送邮件携带附件如何做
时间: 2024-03-01 07:54:05 浏览: 65
要发送带有附件的邮件,可以使用Python中的smtplib和email模块。以下是一个示例代码:
```
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 设置发件人和收件人
sender = 'sender@example.com'
receiver = 'receiver@example.com'
# 创建一个带有附件的邮件
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = '带有附件的邮件'
# 添加邮件正文
text = MIMEText('这是一封带有附件的邮件')
msg.attach(text)
# 添加附件
with open('path/to/attachment.pdf', 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='pdf')
attachment.add_header('Content-Disposition', 'attachment', filename='attachment.pdf')
msg.attach(attachment)
# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'username'
password = 'password'
smtp = smtplib.SMTP(smtp_server, smtp_port)
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
```
需要注意的是,如果附件较大,建议使用多线程或异步模式处理,以避免长时间的等待。
阅读全文