2012-03-02 73 views
27

我发送纯文本电子邮件附加一个txt文件,如下所示:在Python的smtplib

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 = [email protected], [email protected] 
    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文件?

回答

33

用同样的方法,用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) 
+4

作为一个方面说明,我不得不附加内容* *后的附件或它的纯文本身体没有显示。 – David542 2012-03-03 00:17:49

+0

哪个导入是正确的? email.MIMEText或email.mime.text? – ThatAintWorking 2013-10-09 18:08:43

+0

email.mime.text适用于我,但email.MIMEText不适用 – 2015-01-16 04:01:59

0

它为我

sender = '[email protected]' 
receivers = 'who' 

msg = MIMEMultipart() 
msg['Subject'] = 'subject' 
msg['From'] = 'spider man' 
msg['To'] = '[email protected]' 
file='myfile.xls' 

msg.attach(MIMEText("Labour")) 
attachment = MIMEBase('application', 'octet-stream') 
attachment.set_payload(open(file, 'rb').read()) 
encoders.encode_base64(attachment) 
attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) 
msg.attach(attachment) 

print('Send email.') 
conn.sendmail(sender, receivers, msg.as_string()) 
conn.close()