Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何添加一个“;正文“;到python mime多部分(有附件)电子邮件_Python_Python 3.x_Mime_Email Attachments_Mime Mail - Fatal编程技术网

如何添加一个“;正文“;到python mime多部分(有附件)电子邮件

如何添加一个“;正文“;到python mime多部分(有附件)电子邮件,python,python-3.x,mime,email-attachments,mime-mail,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 enc

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

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

试着这样做:

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\u body,'html',UTF-8')
附加到
body\u容器上

我就是这样做的:

body = "Text for body"
msg.attach(MIMEText(body,'plain'))
我是在声明主题之后,在附加文件之前做的