【问题标题】:How to add a body text to a multipart email in python 2?如何在 python 2 中向多部分电子邮件添加正文?
【发布时间】:2017-03-11 01:34:00
【问题描述】:

我正在使用 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())

【问题讨论】:

    标签: python python-2.7 email sendmail mime


    【解决方案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)之后插入这个

    【讨论】:

    • 我试过了,它抛出了这个错误:** 'Cannot attach additional subparts to non-multipart/*') email.errors.MultipartConversionError: Cannot attach additional subparts to non-multipart/* * *
    • 好的,我没有完全理解你的问题。更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 2021-03-28
    • 2014-09-19
    • 2020-11-09
    • 2012-08-13
    • 2010-12-20
    • 2011-07-11
    相关资源
    最近更新 更多