如何将"Body"添加到 python mime 多部分(有附件)电子邮件



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

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()

我就是这样做的:

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

我在声明主题之后和附加文件之前做了。

尝试这样的事情:

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

相关内容

  • 没有找到相关文章

最新更新