簡體   English   中英

如何使用Python imaplib回復電子郵件並包含原始郵件?

[英]How do I reply to an email using the Python imaplib and include the original message?

我目前正在使用imaplib從服務器獲取電子郵件並處理內容和附件。

我想回復帶有狀態/錯誤消息的消息,並鏈接到我的網站上生成的內容,如果可以處理的話。 這應該包括原始郵件,但應刪除任何附件(這將是大的),並最好用他們的文件名/大小替換它們。

由於我已經走過MIME消息部分,我假設我需要做的是構建一個包含原始消息副本的新MIME消息樹並刪除/替換附件節點。

在我開始走這條道路之前,我希望有人可以給我一些提示。 有沒有任何類型的庫函數可以做到這一點? 我應該堅持的任何標准行為?

我目前知道/我正在使用imaplibsmtplibemail模塊,但可能已經遺漏了明顯的東西。 這也在Django中運行,因此可以在django.core.email使用任何內容,如果這樣可以更容易。

傳入消息的原始MIME樹結構如下(使用email.iterators._structure(msg) ):

multipart/mixed
    text/html                (message)
    application/octet-stream (attachment 1)
    application/octet-stream (attachment 2)

通過GMail回復會產生以下結構:

multipart/alternative
    text/plain
    text/html

也就是說,他們沒有我想象的那么聰明,只是放棄附件(好)並提供明確重構“引用內容”的文本和HTML版本。

我開始認為這也是我應該做的,只是回復一個簡單的消息,因為在丟棄附件后,保留原始消息沒有多大意義。

不過,不管怎么回答我原來的問題,不妨回答我原來的問題。

首先,使用text / plain占位符替換原始消息中的所有附件:

import email

original = email.message_from_string( ... )

for part in original.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"]

然后創建回復消息:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.message import MIMEMessage

new = MIMEMultipart("mixed")
body = MIMEMultipart("alternative")
body.attach( MIMEText("reply body text", "plain") )
body.attach( MIMEText("<html>reply body text</html>", "html") )
new.attach(body)

new["Message-ID"] = email.utils.make_msgid()
new["In-Reply-To"] = original["Message-ID"]
new["References"] = original["Message-ID"]
new["Subject"] = "Re: "+original["Subject"]
new["To"] = original["Reply-To"] or original["From"]
new["From"] = "me@mysite.com"

然后附加原始MIME消息對象並發送:

new.attach( MIMEMessage(original) )

s = smtplib.SMTP()
s.sendmail("me@mysite.com", [new["To"]], new.as_string())
s.quit()

得到的結構是:

multipart/mixed
    multipart/alternative
        text/plain
        text/html
    message/rfc822
        multipart/mixed
            text/html
            text/plain
            text/plain

或者使用Django有點簡單:

from django.core.mail import EmailMultiAlternatives
from email.mime.message import MIMEMessage

new = EmailMultiAlternatives("Re: "+original["Subject"],
                             "reply body text", 
                             "me@mysite.com", # from
                             [original["Reply-To"] or original["From"]], # to
                             headers = {'Reply-To': "me@mysite.com",
                                        "In-Reply-To": original["Message-ID"],
                                        "References": original["Message-ID"]})
new.attach_alternative("<html>reply body text</html>", "text/html")
new.attach( MIMEMessage(original) ) # attach original message
new.send()

結果(至少在GMail中)顯示原始消息為“---- Forwarded message ----”,這不是我所追求的,但總體思路有效,我希望這個答案有助於某人嘗試弄清楚如何擺弄MIME消息。

暫無
暫無

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

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