2016-10-28 24 views
0

我成功地發送附件使用python 2郵件但郵件仍然沒有正文內容。如何在Python 2中將正文文本添加到多部分電子郵件中?

有人可以告訴我如何添加正文文本以及附件和主題。

我當前的代碼是:

import smtplib, os 
from email.MIMEMultipart import MIMEMultipart 
from email.MIMEBase import MIMEBase 
from email import Encoders 
from email.mime.text import MIMEText 


SUBJECT = "Email Data" 
emaillist=['[email protected]'] 
msg = MIMEMultipart('mixed') 
msg['Subject'] = 'SUBJECT ' 
msg['From'] = '[email protected]' 
msg['To'] = ', '.join(emaillist) 



part = MIMEBase('application', "octet-stream") 

part.set_payload(open('C:'+os.sep+'Desktop'+os.sep+'temp1.txt', `"rb").read())` 
Encoders.encode_base64(part) 

part.add_header('Content-Disposition', 'attachment; filename="output.txt"') 

msg.attach(part) 

server = smtplib.SMTP("smtp.gmail.com",587) 
server.ehlo() 
server.starttls() 
server.login("[email protected]", "password") 

server.sendmail(msg['From'], emaillist , msg.as_string()) 

回答

1

https://docs.python.org/2/library/email-examples.html

text = "Here is the message body" 
html = """ 
<html> 
    <head></head> 
    <body> 
    <p>here is some html<br> 
     Here is some link <a href="https://www.python.org">link</a>. 
    </p> 
    </body> 
</html> 
""" 

part1 = MIMEText(text, 'plain') 
part2 = MIMEText(html, 'html') 
msg.attach(part1) 
msg.attach(part2) 

插入此之後msg.attach(part)

+0

我試過了,並把它扔到了這個錯誤:**「不能附加其他子部分到非多部分/ *') email.errors.MultipartConversionError:無法將附加子部分附加到非多部分/ * ** – Abhijit

+0

好吧,我完全不瞭解你的問題。更新了答案。 – user3036878

+0

非常感謝。有效。 – Abhijit

相關問題