簡體   English   中英

使用 python 3.4 回復 email

[英]Reply to email using python 3.4

我正在嘗試使用 Python 3.4 回復 email。 email 的收件人將使用 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)
  • function get_reply_message正在刪除此答案中的所有附件。
  • send_it function 設置 Message-ID header 並使用正確的 SMTP 配置。 然后它調用smtplib.sendmail(fr, to, msg.as_string())
  • Outlook 收到 email 但不識別/顯示線程。 但是,該線程似乎是消息的附件(可能由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標題,附加工作內容。

希望這能節省別人的時間

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM