如何使用Python结合QQ邮箱SMTP服务实现带有附件的邮件自动发送?请提供详细的代码示例。
时间: 2024-11-02 18:27:11 浏览: 27
实现使用Python结合QQ邮箱SMTP服务发送带有附件的邮件,首先需要确保已经开启了QQ邮箱的SMTP服务,并获取授权码。接着利用Python标准库中的`smtplib`和`email`模块来构建和发送邮件。以下是详细步骤和代码示例:
参考资源链接:[Python QQ邮箱自动化发邮件教程:带文本与附件示例](https://wenku.csdn.net/doc/4e6d8sy9ih?spm=1055.2569.3001.10343)
1. 导入必要的模块:
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
```
2. 设置SMTP服务器和授权码:
```python
smtp_server = '***'
smtp_port = 465 # SMTP SSL端口
username = 'your_qq_***' # 发送方邮箱账号
password = 'your_qq_email_password' # 授权码
receiver_email = 'receiver_***' # 收件人邮箱账号
```
3. 创建邮件对象并设置邮件头部信息:
```python
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = receiver_email
msg['Subject'] = '这是邮件主题'
```
4. 设置邮件正文内容,并将文本内容添加到邮件对象中:
```python
body = '这是邮件正文内容'
msg.attach(MIMEText(body, 'plain'))
```
5. 添加附件,读取附件文件并转换为`bytes`,然后添加到邮件对象中:
```python
filename = 'example.txt'
with open(filename, 'rb') as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(part)
```
6. 通过SMTP_SSL连接服务器并发送邮件:
```python
try:
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
server.login(username, password)
server.sendmail(username, receiver_email, msg.as_string())
print('邮件发送成功')
except Exception as e:
print(f'邮件发送失败,原因:{e}')
```
确保在发送邮件前已经将收件人邮箱、发件人邮箱及授权码正确设置,同时附件路径正确无误。以上代码将帮助你完成使用Python结合QQ邮箱SMTP服务实现带有附件的邮件自动发送。若想深入了解和实践更多邮件处理技巧,可以参考《Python QQ邮箱自动化发邮件教程:带文本与附件示例》进一步学习。
参考资源链接:[Python QQ邮箱自动化发邮件教程:带文本与附件示例](https://wenku.csdn.net/doc/4e6d8sy9ih?spm=1055.2569.3001.10343)
阅读全文