Python实现发邮件附件
时间: 2024-05-13 17:11:25 浏览: 142
在 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
smtp_user = 'your_email@qq.com'
smtp_password = 'your_password'
# 发送方、接收方、主题、正文、附件信息
sender = 'your_email@qq.com'
receivers = ['recipient_email@qq.com']
subject = 'Python 发送带附件邮件示例'
body = '这是一封 Python 发送带附件邮件的示例邮件'
attachment_file = 'example.txt'
# 构造邮件
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = ','.join(receivers)
msg['Subject'] = subject
# 添加正文
msg.attach(MIMEText(body, 'plain'))
# 添加附件
with open(attachment_file, 'rb') as f:
attachment = MIMEApplication(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=attachment_file)
msg.attach(attachment)
# 发送邮件
server = smtplib.SMTP_SSL(smtp_server, smtp_port)
server.login(smtp_user, smtp_password)
server.sendmail(sender, receivers, msg.as_string())
server.quit()
print('邮件发送成功!')
```
在上面的代码中,需要替换的是发件人邮箱、收件人邮箱、邮箱账号密码以及附件文件名。通过运行这段代码,即可实现向指定邮箱发送带有附件的邮件。
阅读全文