python发送qq邮件带附件
时间: 2023-09-28 10:04:22 浏览: 229
python发送带附件的邮件
可以使用Python的smtplib和email模块来发送带附件的邮件。下面是一个简单的示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 邮件配置信息
smtp_server = 'smtp.qq.com'
smtp_port = 465
sender = 'your_qq_email@qq.com'
password = 'your_qq_email_password'
receiver = 'recipient_email@qq.com'
# 构造邮件对象
msg = MIMEMultipart()
msg['Subject'] = 'Python发送带附件的邮件'
msg['From'] = sender
msg['To'] = receiver
# 添加邮件正文
text = MIMEText('这是一封带附件的测试邮件。')
msg.attach(text)
# 添加附件
with open('test.txt', 'rb') as f:
attachment = MIMEApplication(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename='test.txt')
msg.attach(attachment)
# 发送邮件
smtp = smtplib.SMTP_SSL(smtp_server, smtp_port)
smtp.login(sender, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
print('邮件发送成功!')
```
需要注意的是,QQ邮箱需要使用SMTP_SSL协议发送邮件,所以需要使用`SMTP_SSL`类来创建SMTP对象。同时,为了能够发送附件,需要使用`MIMEMultipart`和`MIMEApplication`类来构造邮件对象和附件对象。在添加附件时,需要指定附件的文件名。
阅读全文