【问题标题】:Reply to email using python 3.4使用 python 3.4 回复电子邮件
【发布时间】:2015-10-04 16:25:36
【问题描述】:

我正在尝试使用 Python 3.4 回复电子邮件。电子邮件的收件人将使用 Outlook(很遗憾),Outlook 能够识别回复并正确显示线程非常重要。

我目前拥有的代码是:

def send_mail_multi(headers, text, msgHtml="", orig=None):
    """
    """

    msg = MIMEMultipart('mixed')
    # Create message container - the correct MIME type is multipart/alternative.
    body = MIMEMultipart('alternative')

    for k,v in headers.items():
        if isinstance(v, list):
            v = ', '.join(v)
        msg.add_header(k, v)

    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    body.attach(MIMEText(text, 'plain'))
    if msgHtml != "": body.attach(MIMEText(msgHtml, 'html'))
    msg.attach(body)

    if orig is not None:
        msg.attach(MIMEMessage(get_reply_message(orig)))
        # Fix subject
        msg["Subject"] = "RE: "+orig["Subject"].replace("Re: ", "").replace("RE: ", "")
        msg['In-Reply-To'] = orig["Message-ID"]
        msg['References'] = orig["Message-ID"]+orig["References"].strip()
        msg['Thread-Topic'] = orig["Thread-Topic"]
        msg['Thread-Index'] = orig["Thread-Index"]

    send_it(msg['From'], msg['To'], msg)
  • 函数get_reply_message 正在删除所有附件,如this answer
  • send_it 函数设置 Message-ID 标头并使用正确的 SMTP 配置。然后它调用smtplib.sendmail(fr, to, msg.as_string())
  • Outlook 收到电子邮件但无法识别/显示线程。但是,该线程似乎是消息的附件(可能由msg.attach(MIMEMessage(...))

关于如何做到这一点的任何想法?我错过了任何标题吗?

干杯,

安德烈亚斯

【问题讨论】:

    标签: python email outlook smtp reply


    【解决方案1】:

    花了我一段时间,但以下似乎有效:

    def send_mail_multi(headers, text, msgHtml="", orig=None):
        """
        """
    
        msg = MIMEMultipart('mixed')
        # Create message container - the correct MIME type is multipart/alternative.
        body = MIMEMultipart('alternative')
    
        for k,v in headers.items():
            if isinstance(v, list):
                v = ', '.join(v)
            msg.add_header(k, v)
    
        # Attach parts into message container.
        # According to RFC 2046, the last part of a multipart message, in this case
        # the HTML message, is best and preferred.
        if orig is not None:
            text, msgHtml2 = append_orig_text(text, msgHtml, orig, False)
    
            # Fix subject
            msg["Subject"] = "RE: "+orig["Subject"].replace("Re: ", "").replace("RE: ", "")
            msg['In-Reply-To'] = orig["Message-ID"]
            msg['References'] = orig["Message-ID"]#+orig["References"].strip()
            msg['Thread-Topic'] = orig["Thread-Topic"]
            msg['Thread-Index'] = orig["Thread-Index"]
    
        body.attach(MIMEText(text, 'plain'))
        if msgHtml != "": 
            body.attach(MIMEText(msgHtml2, 'html'))
        msg.attach(body)
    
        send_it(msg)
    
    
    def append_orig_text(text, html, orig, google=False):
        """
        Append each part of the orig message into 2 new variables
        (html and text) and return them. Also, remove any 
        attachments. If google=True then the reply will be prefixed
        with ">". The last is not tested with html messages...
        """
        newhtml = ""
        newtext = ""
    
        for part in orig.walk():
            if (part.get('Content-Disposition')
                and part.get('Content-Disposition').startswith("attachment")):
    
                part.set_type("text/plain")
                part.set_payload("Attachment removed: %s (%s, %d bytes)"
                            %(part.get_filename(), 
                            part.get_content_type(), 
                            len(part.get_payload(decode=True))))
                del part["Content-Disposition"]
                del part["Content-Transfer-Encoding"]
    
            if part.get_content_type().startswith("text/plain"):
                newtext += "\n"
                newtext += part.get_payload(decode=False)
                if google:
                    newtext = newtext.replace("\n","\n> ")
    
            elif part.get_content_type().startswith("text/html"):
                newhtml += "\n"
                newhtml += part.get_payload(decode=True).decode("utf-8")
                if google:
                    newhtml = newhtml.replace("\n", "\n> ")
    
        if newhtml == "":
            newhtml = newtext.replace('\n', '<br/>')
    
        return (text+'\n\n'+newtext, html+'<br/>'+newhtml)
    

    代码需要稍微整理一下,但 Outlook 可以正确显示它(使用 Next/Previous 选项)。无需手动创建From, Send, To, Subject 标头,附加有效的内容。

    希望这可以节省别人的时间

    【讨论】:

    • 只是一个小修正:如果您希望 Outlook 显示漂亮的(蓝色)电子邮件标题,您必须构建它(在

      内)。这仅适用于 HTML 电子邮件...

    • 你能解释一下你的原始代码和这个有什么区别吗?
    • 已经有一段时间了,但据我所知(再次:))append_orig_text 似乎有所作为。它不是附加原始消息,而是将原始消息的所有文本/纯文本部分隔离到附加的新 MIMEText 中。我希望我能提供更多信息,但已经有一段时间了,现在我无处可测试......
    猜你喜欢
    • 1970-01-01
    • 2016-03-22
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2013-07-25
    • 1970-01-01
    相关资源
    最近更新 更多