【问题标题】:How to add a "Body" to a python mime multipart(has attachment) email如何将“正文”添加到 python mime multipart(有附件)电子邮件
【发布时间】:2015-07-09 03:15:23
【问题描述】:

我正在使用以下 sn-p 发送带有附件的电子邮件。我想在正文中添加一条描述附件的消息,我该怎么做?目前我收到的电子邮件是空白正文。

msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = emailto
    msg["Subject"] = subject



    ctype, encoding = mimetypes.guess_type(fileToSend)
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"

    maintype, subtype = ctype.split("/", 1)

    if maintype == "text":
        fp = open(fileToSend)
        # Note: we should handle calculating the charset
        attachment = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "image":
        fp = open(fileToSend, "rb")
        attachment = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "audio":
        fp = open(fileToSend, "rb")
        attachment = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(fileToSend, "rb")
        attachment = MIMEBase(maintype, subtype)
        attachment.set_payload(fp.read())
        fp.close()
        encoders.encode_base64(attachment)
    attachment.add_header("Content-Disposition", "attachment", filename=os.path.basename(fileToSend))
    msg.attach(attachment)

    server = smtplib.SMTP('localhost')
    server.sendmail(emailfrom, emailto, msg.as_string())
    server.quit()

【问题讨论】:

    标签: python python-3.x mime email-attachments mime-mail


    【解决方案1】:

    我就是这样做的:

    body = "Text for body"
    msg.attach(MIMEText(body,'plain'))
    

    我是在声明主题之后和附加文件之前完成的。

    【讨论】:

      【解决方案2】:

      试试这样的:

      from email.MIMEMultipart import MIMEMultipart
      from email.MIMEText import MIMEText    
      
      ...
      
      msg = MIMEMultipart("related")
      msg["From"] = emailfrom
      msg["To"] = emailto
      msg["Subject"] = subject
      
      body_container = MIMEMultipart('alternative')
      body_container.attach(MIMEText(
              plain_text_body.encode('utf-8'), 'plain', 'UTF-8'))
      msg.attach(body_container)
      
      ...
      

      然后附上您的附件。您还可以附加“普通”和“html”正文。在这种情况下,您需要将第二个 MIMEText(html_body, 'html', 'UTF-8') 附加到 body_container

      【讨论】:

        猜你喜欢
        • 2017-11-07
        • 2015-05-28
        • 2016-02-19
        • 1970-01-01
        • 1970-01-01
        • 2019-04-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多