程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

使用python 3.4回复电子邮件

发布于2019-10-14 17:47     阅读(1235)     评论(0)     点赞(30)     收藏(4)


我正在尝试使用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正在删除此答案中的所有附件
  • send_it函数设置Message-ID标头并使用正确的SMTP配置。然后它调用smtplib.sendmail(fr, to, msg.as_string())
  • Outlook收到电子邮件,但无法识别/显示线程。但是,该线程似乎是邮件的附件(可能是由于msg.attach(MIMEMessage(...))

有关如何执行此操作的任何想法?我错过任何标题了吗?

干杯,

安德烈亚斯


解决方案


花了我一段时间,但以下似乎工作:

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可以正确显示它(使用“下一个/上一个”选项)。无需From, Send, To, Subject手动创建标题,即可附加有效的内容。

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



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/136451/78c8d6a3309f9c022e2c/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

30 0
收藏该文
已收藏

评论内容:(最多支持255个字符)