如何将“Body”添加到python mime multipart(附件)电子邮件中

时间:2015-04-29 17:21:39

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

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

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

0 个答案:

没有答案