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!
Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AMIs it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.
Python for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AMKey applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code
Python vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AMPython is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.
Python in Action: Real-World ExamplesApr 18, 2025 am 12:18 AMPython's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.
Python's Main Uses: A Comprehensive OverviewApr 18, 2025 am 12:18 AMPython is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.
The Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AMPython's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.
Python: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AMPython is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.
Learning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AMYes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools






