如何用python发送带有附件的邮件
时间: 2024-04-30 10:20:50 浏览: 7
可以使用Python的内置库`email`和`smtplib`来发送带有附件的邮件。下面是一个示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 邮件正文
body = "这是一封带附件的邮件"
# 创建邮件对象
msg = MIMEMultipart()
msg['Subject'] = '带附件的邮件'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
# 添加邮件正文
msg.attach(MIMEText(body, 'plain'))
# 添加附件
with open('example.txt', 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment', filename='example.txt')
msg.attach(attachment)
# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'sender@example.com'
smtp_password = 'password'
smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
smtp_conn.starttls()
smtp_conn.login(smtp_username, smtp_password)
smtp_conn.sendmail('sender@example.com', 'recipient@example.com', msg.as_string())
smtp_conn.quit()
```
上面的代码中,我们将邮件正文和附件添加到了邮件对象`msg`中,并将其发送到了收件人的邮箱中。需要自行修改邮件服务器的地址、端口、用户名和密码等信息。