在Python smtplib中附加一个txt文件 [英] Attach a txt file in Python smtplib
本文介绍了在Python smtplib中附加一个txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在发送纯文本电子邮件,如下所示:
I am sending a plain text email as follows:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_message():
msg = MIMEMultipart('alternative')
s = smtplib.SMTP('smtp.sendgrid.net', 587)
s.login(USERNAME, PASSWORD)
toEmail, fromEmail = to@email.com, from@email.com
msg['Subject'] = 'subject'
msg['From'] = fromEmail
body = 'This is the message'
content = MIMEText(body, 'plain')
msg.attach(content)
s.sendmail(fromEmail, toEmail, msg.as_string())
除了这个消息,我想附加一个txt文件'log_file.txt'。如何在这里附加一个txt文件?
In addition to this message, I would like to attach a txt file, 'log_file.txt'. How would I attach a txt file here?
推荐答案
同样的方式,使用 msg.attach
:
The same way, using msg.attach
:
from email.mime.text import MIMEText
filename = "text.txt"
f = file(filename)
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
这篇关于在Python smtplib中附加一个txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文