python发送邮件带附件
时间: 2023-07-06 14:43:53 浏览: 33
python发送带附件的邮件
好的,以下是Python发送带附件的邮件的代码示例:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 发件人邮箱账号
sender = 'your_email@example.com'
# 发件人邮箱密码或授权码
password = 'your_email_password_or_authorization_code'
# 收件人邮箱账号
receiver = 'recipient_email@example.com'
# 创建一个带附件的邮件实例
message = MIMEMultipart()
message['From'] = sender
message['To'] = receiver
message['Subject'] = '邮件主题'
# 邮件正文内容
text = MIMEText('这是一封带附件的邮件')
message.attach(text)
# 构造附件,传送当前目录下的 test.txt 文件
with open('test.txt', 'rb') as f:
attachment = MIMEApplication(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename='test.txt')
message.attach(attachment)
# 发送邮件
try:
smtp_obj = smtplib.SMTP('smtp.example.com', 25)
smtp_obj.login(sender, password)
smtp_obj.sendmail(sender, receiver, message.as_string())
print('邮件发送成功')
except smtplib.SMTPException as e:
print('邮件发送失败,错误信息:', e)
```
其中,`sender`、`password`、`receiver`需要根据实际情况进行修改,`smtp.example.com`是发件人邮箱的 SMTP 服务器地址,需要根据发件人邮箱的实际情况进行修改。在构造附件时,需要将文件名和路径修改为实际的文件名和路径。
阅读全文