在解析并对其进行一些更改后,为多部分电子邮件设置的内容类型应该是什么?

What should be the content type to set for a multipart email after parsing and making some changes to it?

我有一封包含所有类型附件的多部分电子邮件。多个电子邮件、纯文本、pdf 附件、内联图像和 html。遍历多部分正文的不同部分并向主电子邮件的正文添加一些文本后,我希望将整个电子邮件重新生成为原始邮件。正确的方法应该是什么。使用 python 3.6。我尝试过的代码片段如下:

mail_attached_bool = False
new_message1 = email.message.EmailMessage()
attached_bool = False

mhtml = 'Modified html variable'
mbody = 'Modified text variable'

# while parsing the multipart of the raw message: msg
if msg.is_multipart():
    for part in msg.walk():
        if part.get_content_type() == 'multipart/report':
            new_message.attach(mbody)
            if mhtml:            
                new_message.attach(mhtml)

            for rel1 in part.walk():
                if rel1.get_content_type() == 'message/delivery-status':
                    new_message.attach(rel1)
                if rel1.get_content_type() == 'text/rfc822-headers':
                    new_message.attach(rel1)

        if part.get_content_type() in ["multipart/related",
                                       "multipart/mixed"]:
            new_message1.set_type("multipart/related")
            if mhtml:
                new_message1.attach(mhtml)
                print(999999)
            elif mbody:
                if mbody == '':
                    mbody = MIMEText(warning_txt,'plain')
                new_message1.attach(mbody)

        for rel in part.walk():
            mail_attached_bool = False
            attached_bool = False
            print(rel.get_content_type(), '------------cccccccc')
            # other kinds of attachments
            cdispo = str(rel.get('Content-Disposition'))
            attach = re.compile('application/*')
            attachment = attach.search(rel.get_content_type())

            if rel.get_content_type() in ['message/rfc822',]:
                new_message1.set_type('multipart/related')
                print(rel.get_content_type(), '----------content type')
                mail_attached_bool = True
                attached_bool = True
                x += 1
            
            if rel.is_multipart() and rel.get_content_type() \
               not in \
               ["multipart/alternative",
                "message/rfc822"
               ]:
                new_message1.set_type(rel.get_content_type())

            # ignore the first html as its the mail body
            if rel.get_content_type() == "text/html" and cdispo=='None':
                i += 1
                if i == 1 and html_body:
                    continue
                print('i: ',i)
            # ignore the first plain text as its the mail body
            if rel.get_content_type() == "text/plain" and cdispo=='None':
                j += 1
                if j == 1 and text_body:
                    continue
                print('j: ',j)

            #--------------#                    
            if 1:#rel.get_content_type() != 'message/rfc822':#mail_attached_bool is False:
                # has mail content apart from body (ios)
                if rel.get_content_type() == "text/html":
                    new_message1.attach(rel)
                    print(rel.get_filename(),'-----   html  attached')

                if rel.get_content_type() == "text/plain" and \
                   rel.get('Content-Disposition') in [None, "inline"]:
                    new_message1.attach(rel)
                    print('---------------text attachment', 666666)

                if rel.get_content_type() in ['image/png',
                                              'image/jpeg',
                                              'image/jpg'] \
                                              or ('attachment' in cdispo) \
                                    or ('inline' in cdispo) or (attachment):

                    # inline images and text
                    if "inline" in cdispo and \
                       not rel.get_content_type() in [
                           "text/plain",
                       ] \
                           and not attached_bool:
                        attached_bool = True
                        new_message1.attach(rel)
                        
                    if attachment or "attachment" in cdispo and \
                       (not attached_bool) or cdispo == 'None':
                        new_message1.attach(rel)
                        attached_bool = True

                    elif cdispo == 'None' and (not attached_bool):
                        new_message1.attach(rel)
                        print('attaching here')

                if rel.get_content_type() in ['text/calendar']:
                    new_message1.attach(rel)

            if mail_attached_bool:
                new_message1.attach(rel)

        new_message.set_type('multipart/alternative')
        new_message.attach(new_message1)
        if new_message1:
            print('new_message1 exists')
            break

然后发送邮件。 发送邮件时,它会在新邮件对象中附加主邮件正文及其附件 2 次。为什么会这样?为新邮件设置的正确内容类型是什么?

我不太确定你的问题是什么,但我会给你一些代码,可能是一个很好的起点:

import smtplib
import ssl

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

subject = "test..."
receiver_email = "someone@something.com"
sender_email = "yourself@something.com"
sender_password = "yourpassword123"
htmlmessage = "<h1>This is a test</h1>"
imagedata = open("someimagefile.png", "rb").read()


message = MIMEMultipart("alternative")

message["Subject"] = subject
message["From"] = sender_email
message["To"] = receiver_email


part1 = MIMEText(htmlmessage, "html")
message.attach(part1)

msg_image = MIMEImage(imagedata)
message.attach(msg_image)

context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, sender_password)
    server.sendmail(sender_email, receiver_email, message.as_string()

)

此代码创建多部分消息。它添加 HTML 代码作为消息正文 (MIMEText(htmlmessage, "html")) 和图像作为附件 (MIMEImage(imagedata))。然后它发送消息。

我真的不能给你更具体的代码,因为你对这个问题的解释有点含糊,但希望这会有所帮助。您可以尝试在您的代码中使用此示例的部分内容。例如,尝试将 new_message.attach(mhtml) 替换为 new_message.attach(MIMEText(mhtml, "html"))

希望这至少能有所帮助。

答案很简单:

new_text = "[Hi please find added text before main mail body]"
 new_message.attach(new_text)
 old_message = MIMEMessage(mail)
 new_message.attach(old_message)

并为 new_message 使用 sendmail() 仅适用于内联图片和空白正文内容的电子邮件,需要添加条件代码,即将更新。