python - 使用 python 3.4 回复电子邮件

标签 python email outlook smtp reply

我正在尝试使用 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 header 并使用正确的 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 header ,附加工作内容。

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

关于python - 使用 python 3.4 回复电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31433633/

相关文章:

python - 从 ubuntu 终端命令提示符中删除 anaconda 环境前缀

python - Django ModelForm 中的一个字段(ManyToMany)未保存到数据库

java - 在 Hudson 的通知电子邮件中包含最新测试结果信息

php - 如何启用 XAMPP 在本地使用 php 的 mail() 函数,这样我就可以在本地测试我的 mail() 脚本而无需上传到我的服务器?

vba - 如何默默拒绝 session ?

python - Python中的可中断线程连接

python - 如何在 django admin 中订购只读 M2M 字段

cocoa - cocoa 中的数据检测器

Outlook 2013 中的 HTML 电子邮件未对齐?

.net - 获取 Outlook.PropertyPageSite,以便您可以调用 OnStatusChange() 并更新 UI