用 python 发送以txt文件为内容的电子邮件
时间: 2024-02-19 17:03:51 浏览: 71
Python3利用SMTP协议发送E-mail电子邮件的方法
可以使用Python的smtplib和email模块来发送以txt文件为内容的电子邮件。以下是一个基本的示例代码:
```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'
receiver = 'recipient@example.com'
subject = 'Email with Attachment'
body = 'Please find the attached txt file.'
# 创建邮件
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
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)
# 发送邮件
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.starttls()
smtp.login(sender, 'your_password')
smtp.send_message(msg)
```
需要将`your_email@example.com`替换为发件人的电子邮件地址,`recipient@example.com`替换为收件人的电子邮件地址,`example.txt`替换为要发送的txt文件的文件名,`smtp.gmail.com`替换为对应的SMTP服务器地址,`your_password`替换为发件人的电子邮件密码。
阅读全文