帮我写一个发送带附件的qq邮箱邮件的python代码
时间: 2023-08-28 19:31:03 浏览: 102
python3通过qq邮箱发送邮件以及附件
5星 · 资源好评率100%
当然可以!你需要先安装 `smtplib` 和 `email` 模块。然后可以使用以下代码发送带附件的qq邮箱邮件:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 发送方的邮箱账号和密码
sender_email = 'your_qq_email@qq.com'
sender_password = 'your_qq_password'
# 接收方的邮箱账号
receiver_email = 'receiver_email@example.com'
# 创建一个带附件的邮件对象
msg = MIMEMultipart()
msg['Subject'] = '带附件的邮件'
msg['From'] = sender_email
msg['To'] = receiver_email
# 添加邮件正文
body = '这是一封带附件的邮件'
msg.attach(MIMEText(body, 'plain'))
# 添加附件
filename = 'example.txt'
with open(filename, 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
# 发送邮件
with smtplib.SMTP_SSL('smtp.qq.com', 465) as smtp:
smtp.login(sender_email, sender_password)
smtp.sendmail(sender_email, receiver_email, msg.as_string())
```
其中,需要将 `sender_email`、`sender_password` 和 `receiver_email` 替换为你自己的邮箱账号和密码、以及接收方的邮箱账号。在添加附件时,需要将 `example.txt` 替换为你自己的附件文件名。
阅读全文