使用python 3.4回复电子邮件 [英] Reply to email using python 3.4

查看:154
本文介绍了使用python 3.4回复电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python 3.4回复电子邮件。电子邮件的收件人将使用Outlook(不幸的是),重要的是Outlook可以识别回复并正确显示线程。



我现在的代码是: / p>

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



msg = MIMEMultipart('mixed')
#创建消息容器 - 正确的MIME类型是multipart / alternative。
body = MIMEMultipart('alternative')

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

#将零件附加到消息容器中。
#根据RFC 2046,多部分消息的最后部分(在这种情况下为
#的HTML消息)是最好的和首选的。
body.attach(MIMEText(text,'plain'))
如果msgHtml!=:body.attach(MIMEText(msgHtml,'html'))
msg.attach )

如果orig不是None:
msg.attach(MIMEMessage(get_reply_message(orig)))
#修复主题
msg [主题] = RE:+ Orig [Subject]。replace(Re:,).replace(RE:,)
msg ['In-Reply-To'] = orig [消息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(...))

b b b b b b b b b b b b b??????????????????????b b b b b b b b b b b
$ b

Andreas

解决方案

让我有一段时间,但以下内容似乎工作:

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



msg = MIMEMultipart('mixed')
#创建消息容器 - 正确的MIME类型是multipart / alternative。
body = MIMEMultipart('alternative')

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

#将部件附加到消息容器中
#根据RFC 2046,多部分消息的最后部分(在这种情况下为
#的HTML消息)是最好的,比较喜欢
如果orig不是None:
text,msgHtml2 = append_orig_text(text,msgHtml,orig,False)

#修复主题
msg [主题 ] =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' )
如果msgHtml!=:
body.attach(MIMEText(msgHtml2,'html'))
msg.attach(body)

send_it


def append_orig_text(text,html,orig,google = False):

将orig消息的每个部分附加到2个新变量
(html和text)并返回它们。另外,删除任何
附件。如果google = True,那么回复将以$&B $ b为前缀。最后一个没有用html消息测试...

newhtml =
newtext =

在orig.walk() :
if(part.get('Content-Disposition')
和part.get('Content-Disposition')。startswith(attachment)):

部分.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]

如果part.get_content_type()。startswith(text / plain):
newtext + =\\\

newtext + = part.get_payload(decode = False)
如果google:
newtext = newtext.replace(\\\
,\\\
>)

elif part.get_content_type()。 startswith(text / html):
newhtml + =\\\

newhtml + = part.get_payload(decode = True).decode(utf-8)
if google:
newhtml = newhtml.replace(\\\
,\\\
> )

如果newhtml ==:
newhtml = newtext.replace('\\\
','< br />')

return(text +'\\\
\\\
'+ newtext,html +'< br />'+ newhtml)

代码需要一点点起来,但是Outlook正确显示它(使用Next / Previous选项)。没有必要创建 From,Send,To,Subject 标题,手工附加内容。



希望保存别人的时间


I am trying to reply to an email using Python 3.4. The recipient of the email will be using Outlook (unfortunately) and it is important that Outlook recognizes the reply and displays the thread properly.

The code I currently have is:

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)

  • The function get_reply_message is removing any attachments as in this answer.
  • send_it function sets the Message-ID header and uses the proper SMTP configuration. Then it calls smtplib.sendmail(fr, to, msg.as_string())
  • Outlook receives the email but does not recognize/display the thread. However, the thread seems like being an attachment to the message (probably caused by msg.attach(MIMEMessage(...))

Any ideas on how to do this? Have I missed any headers?

Cheers,

Andreas

解决方案

Took me a while but the following seems working:

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)

The code needs a little bit tiding up but as is Outlook displays it correctly (with Next/Previous options). There was no need to create From, Send, To, Subject headers by hand, appending the content worked.

Hope this saves someone else's time

这篇关于使用python 3.4回复电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆