This article introduces you to Python’s use of the email module to encode and decode emails. It is very detailed. Friends who have the same needs can refer to
Decoding emails
The email module that comes with Python is a very interesting thing. It can encode and decode emails and is very useful for processing emails.
Processing emails is a very detailed job, especially decoding emails, because its format changes too much. Let’s take a look at the source file of an email:
Received: from 192.168.208.56 ( 192.168.208.56 [192.168.208.56] ) by ajax-webmail-wmsvr37 (Coremail) ; Thu, 12 Apr 2007 12:07:48 +0800 (CST) Date: Thu, 12 Apr 2007 12:07:48 +0800 (CST) From: user1 <xxxxxxxx@163.com> To: zhaowei <zhaoweikid@163.com> Message-ID: <31571419.200911176350868321.JavaMail.root@bj163app37.163.com> Subject: =?gbk?B?u+nJtA==?= MIME-Version: 1.0 Content-Type: multipart/Alternative; boundary="----=_Part_21696_28113972.1176350868319" ------=_Part_21696_28113972.1176350868319 Content-Type: text/plain; charset=gbk Content-Transfer-Encoding: base64 ztLS0b+qyrzS1M6qysfSu7j20MfG2ru70ru0zqOs1K3AtMrH0ru49tTCtffSu7TOztLDx8/W1NrT prjDysew67XjssXE3MjI1ebC6bezICAg ------=_Part_21696_28113972.1176350868319 Content-Type: text/html; charset=gbk Content-Transfer-Encoding: quoted-printable <p>=CE=D2=D2=D1=BF=AA=CA=BC=D2=D4=CE=AA=CA=C7=D2=BB=B8=F6=D0=C7=C6=DA=BB= =BB=D2=BB=B4=CE=A3=AC=D4=AD=C0=B4=CA=C7=D2=BB=B8=F6=D4=C2=B5=F7=D2=BB=B4=CE= </p> <p>=CE=D2=C3=C7=CF=D6=D4=DA=D3=A6=B8=C3=CA=C7=B0=EB=B5=E3=B2=C5=C4=DC=C8= =C8</p> <p>=D5=E6=C2=E9=B7=B3</p> ------=_Part_21696_28113972.1176350868319--
The above is the source file of an email. The first line to the first blank line is the header of the email, and the rest is the body of the email. Copy the above information and save it to a file called xxx.eml. You can see the content by double-clicking it with the mouse. Of course, what you see is the decoded version. Outlook decoded it for you.
Let’s see how the email module handles this email. Assume that the letter has been saved as xxx.eml.
#-*- encoding: gb2312 -*- import email fp = open("xxx.eml", "r") msg = email.message_from_file(fp) # 直接文件创建message对象,这个时候也会做初步的解码 subject = msg.get("subject") # 取信件头里的subject, 也就是主题 # 下面的三行代码只是为了解码象=?gbk?Q?=CF=E0=C6=AC?=这样的subject h = email.Header.Header(subject) dh = email.Header.decode_header(h) subject = dh[0][0] print "subject:", subject print "from: ", email.utils.parseaddr(msg.get("from"))[1] # 取from print "to: ", email.utils.parseaddr(msg.get("to"))[1] # 取to fp.close()
This code can parse out the subject, sender, and recipient of an email. email.utils.parseaddr is used to specifically parse email addresses. The reason is that email addresses are often written like this in the original text: user1
The previous code only parses the letter header, and then parses the letter body. The letter body may have two plain text parts and html parts, and may also have attachments. Knowledge of mime is required here. Detailed introduction can be found online. I won’t go into details here. Let’s take a look at how to parse:
#-*- encoding: gb2312 -*- import email fp = open("xxx.eml", "r") msg = email.message_from_file(fp) # 循环信件中的每一个mime的数据块 for par in msg.walk(): if not par.is_multipart(): # 这里要判断是否是multipart,是的话,里面的数据是无用的,至于为什么可以了解mime相关知识。 name = par.get_param("name") #如果是附件,这里就会取出附件的文件名 if name: #有附件 # 下面的三行代码只是为了解码象=?gbk?Q?=CF=E0=C6=AC.rar?=这样的文件名 h = email.Header.Header(name) dh = email.Header.decode_header(h) fname = dh[0][0] print '附件名:', fname data = par.get_payload(decode=True) # 解码出附件数据,然后存储到文件中 try: f = open(fname, 'wb') #注意一定要用wb来打开文件,因为附件一般都是二进制文件 except: print '附件名有非法字符,自动换一个' f = open('aaaa', 'wb') f.write(data) f.close() else: #不是附件,是文本内容 print par.get_payload(decode=True) # 解码出文本内容,直接输出来就可以了。 print '+'*60 # 用来区别各个部分的输出
It’s simple. It doesn’t take much code to achieve complex parsing of emails. function!
Encoding Email
It is also very simple to use the email module to generate emails. It just requires some basic knowledge of mime. Let's take a look at some mime basics.
MIME messages are composed of two parts: message header and message body. In emails, they are the message header and message body. Separate the email header and email body with blank lines. This can be clearly seen by viewing the source file of an email using a text editor (such as Notepad). Outlook and Foxmail have their own functions to view source files.
The email header contains important information such as the sender, recipient, subject, time, MIME version, and type of email content. Each piece of information is called a domain, which consists of the domain name followed by ":" and the information content. It can be one line, or a longer one can occupy multiple lines. The first line of the field must be written "top", that is, there must be no whitespace characters (spaces and tabs) on the left; continuation lines must start with a whitespace character, and the first whitespace character is not inherent to the information itself.
The email body contains the content of the email, and its type is indicated by the "Content-Type" field of the email header. The most common types are text/plain (plain text) and text/html (hypertext). The email body is divided into multiple segments, and each segment contains a segment header and a segment body, which are also separated by blank lines. There are three common multipart types: multipart/mixed, multipart/related and multipart/alternative. From their names, it is not difficult to deduce the respective meanings and uses of these types.
If you want to add attachments to the email, you must define the multipart/mixed segment; if there are embedded resources, at least the multipart/related segment must be defined; if plain text and hypertext coexist, at least the multipart/alternative segment must be defined. Generating emails is to generate these various MIME parts. The email module has packaged these processes. Take a look at the generation method:
#-*- encoding: gb2312 -*- import email import string, sys, os, email import time class MailCreator: def __init__(self): # 创建邮件的message对象 self.msg = email.Message.Message() self.mail = "" def create(self, mailheader, maildata, mailattachlist=[]): # mailheader 是dict类型,maildata是list, 且里面第一项为纯文本类型,第二项为html. # mailattachlist 是list, 里面为附件文件名 if not mailheader or not maildata: return for k in mailheader.keys(): # 对subject要作特殊处理,中文要转换一下。 # 比如 "我的一个测试邮件" 就要转换为 =?gb2312?b?ztK1xNK7uPay4srU08q8/g==?= if k == 'subject': self.msg[k] = email.Header.Header(mailheader[k], 'gb2312') else: self.msg[k] = mailheader[k] # 创建纯文本部分 body_plain = email.MIMEText.MIMEText(maildata[0], _subtype='plain', _charset='gb2312') body_html = None # 创建html部分,这个是可选的 if maildata[1]: body_html = email.MIMEText.MIMEText(maildata[1], _subtype='html', _charset='gb2312') # 创建一个multipart, 然后把前面的文本部分和html部分都附加到上面,至于为什么,可以看看mime相关内容 attach=email.MIMEMultipart.MIMEMultipart() attach.attach(body_plain) if body_html: attach.attach(body_html) # 处理每一个附件 for fname in mailattachlist: attachment=email.MIMEText.MIMEText(email.Encoders._bencode(open(fname,'rb').read())) # 这里设置文件类型,全部都设置为Application.当然也可以是Image,Audio什么的,这里不管那么多 attachment.replace_header('Content-type','Application/octet-stream;name="'+os.path.basename(fname)+'"') # 一定要把传输编码设置为base64,因为这里默认就是用的base64 attachment.replace_header('Content-Transfer-Encoding', 'base64') attachment.add_header('Content-Disposition','attachment;filename="'+os.path.basename(fname)+'"') attach.attach(attachment) # 生成最终的邮件 self.mail = self.msg.as_string()[:-1] + attach.as_string() return self.mail if __name__ == '__main__': mc = MailCreator() header = {'from': 'zhaowei@163.com', 'to':'weizhao@163.com', 'subject':'我的一个测试邮件'} data = ['plain text information', '<font color="red">html text information</font>'] if sys.platform == 'win32': attach = ['c:/windows/clock.avi'] else: attach = ['/bin/cp'] mail = mc.create(header, data, attach) f = open("test.eml", "wb") f.write(mail) f.close()
Here I have encapsulated a class to do the processing. The process is:
1. First create the message object: email.Message.Message()
2. Create the MIMEMultipart object: email.MIMEMultipart.MIMEMultipart()
3. Create each MIMEText object and put them Attach to MIMEMultipart. The MIMEText here is actually not just text, but also includes image, application, audio, etc.
4. Generate final email.
Related recommendations:
Python script to calculate the size of all directories under a specified path_PHP tutorial
Python calculation of character width Methods
The above is the detailed content of Python uses the email module to encode and decode emails. For more information, please follow other related articles on the PHP Chinese website!