2012-03-02 21 views
27

gönderiyorum bir düz metin e-posta bir txt dosyası ekleme:şöyle Python'un 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()) 

Bu mesaja ek olarak, bir txt dosyası, 'log_file.txt' takmak istiyorum. Bir txt dosyasını buraya nasıl eklerim? msg.attach kullanarak

cevap

33

aynı şekilde,:

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

için çalışır, ben sonra * * eki içeriği eklemek zorunda yoksa düz metin içinde vücut göstermiyordu. – David542

+0

Hangi ithalat doğru? email.MIMEText veya email.mime.text? – ThatAintWorking

+0

email.mime.text benim için çalışıyor ancak email.MIMEText çalışmıyor –

0

Benim bir yan not olarak

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()