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

本文介绍了如何使用Python 3.4来回复电子邮件。通过定义`send_mail_multi`和`append_orig_text`函数,实现邮件正文的创建、原始邮件内容的附加以及处理回复时的格式设置。邮件内容可以包含纯文本和HTML两种格式,并能处理附件和Google邮箱的回复样式。
摘要由CSDN通过智能技术生成

defsend_mail_multi(headers,text,msgHtml="",orig=None):"""

"""msg=MIMEMultipart('mixed')# Create message container - the correct MIME type is multipart/alternative.body=MIMEMultipart('alternative')fork,vinheaders.items():ifisinstance(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.iforigisnotNone:text,msgHtml2=append_orig_text(text,msgHtml,orig,False)# Fix subjectmsg["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'))ifmsgHtml!="":body.attach(MIMEText(msgHtml2,'html'))msg.attach(body)send_it(msg)defappend_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=""forpartinorig.walk():if(part.get('Content-Disposition')andpart.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))))delpart["Content-Disposition"]delpart["Content-Transfer-Encoding"]ifpart.get_content_type().startswith("text/plain"):newtext+="\n"newtext+=part.get_payload(decode=False)ifgoogle:newtext=newtext.replace("\n","\n> ")elifpart.get_content_type().startswith("text/html"):newhtml+="\n"newhtml+=part.get_payload(decode=True).decode("utf-8")ifgoogle:newhtml=newhtml.replace("\n","\n> ")ifnewhtml=="":newhtml=newtext.replace('\n','
')return(text+'\n\n'+newtext,html+'
'+newhtml)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值