2012-03-02 31 views
27

Tôi gửi một email văn bản đơn giản như sau:Đính kèm một file txt bằng 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()) 

Ngoài thông báo này, tôi muốn đính kèm một file txt, 'log_file.txt'. Làm cách nào để đính kèm tệp txt ở đây?

Trả lời

33

Theo cùng một cách, sử dụng 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

Như một mặt lưu ý, tôi đã phải đính kèm các nội dung * sau * tập tin đính kèm hoặc nó trở thành văn bản đơn giản trong cơ thể không hiển thị. – David542

+0

Nhập nào là chính xác? email.MIMEText hoặc email.mime.text? – ThatAintWorking

+0

email.mime.text hoạt động với tôi nhưng email.MIMEText không –

0

Nó làm việc cho tôi

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() 
Các vấn đề liên quan