我使用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=['xyz@hotmail.com']
msg = MIMEMultipart('mixed')
msg['Subject'] = 'SUBJECT '
msg['From'] = 'abc@gmail.com'
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("abc@gmail.com", "password")
server.sendmail(msg['From'], emaillist , msg.as_string())
答案 0 :(得分:2)
来自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)