search
HomeBackend DevelopmentPython TutorialPython uses the email module to encode and decode emails

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 , email.utils.parseaddr can parse it into a In the list, the first item is user1, and the second item is xxxxxxxx@163.com. Only the following parts are shown here.
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 &#39;附件名:&#39;, fname
      data = par.get_payload(decode=True) # 解码出附件数据,然后存储到文件中
      
      try:
        f = open(fname, &#39;wb&#39;) #注意一定要用wb来打开文件,因为附件一般都是二进制文件
      except:
        print &#39;附件名有非法字符,自动换一个&#39;
        f = open(&#39;aaaa&#39;, &#39;wb&#39;)
      f.write(data)
      f.close()
    else:
      #不是附件,是文本内容
      print par.get_payload(decode=True) # 解码出文本内容,直接输出来就可以了。
    
    print &#39;+&#39;*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 == &#39;subject&#39;:
        self.msg[k] = email.Header.Header(mailheader[k], &#39;gb2312&#39;)      
      else:
        self.msg[k] = mailheader[k]
    # 创建纯文本部分
    body_plain = email.MIMEText.MIMEText(maildata[0], _subtype=&#39;plain&#39;, _charset=&#39;gb2312&#39;)
    body_html = None
    # 创建html部分,这个是可选的
    if maildata[1]:
      body_html = email.MIMEText.MIMEText(maildata[1], _subtype=&#39;html&#39;, _charset=&#39;gb2312&#39;)
    
    
    # 创建一个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,&#39;rb&#39;).read()))
      # 这里设置文件类型,全部都设置为Application.当然也可以是Image,Audio什么的,这里不管那么多
      attachment.replace_header(&#39;Content-type&#39;,&#39;Application/octet-stream;name="&#39;+os.path.basename(fname)+&#39;"&#39;)
      # 一定要把传输编码设置为base64,因为这里默认就是用的base64
      attachment.replace_header(&#39;Content-Transfer-Encoding&#39;, &#39;base64&#39;)
      attachment.add_header(&#39;Content-Disposition&#39;,&#39;attachment;filename="&#39;+os.path.basename(fname)+&#39;"&#39;)
      attach.attach(attachment)
    # 生成最终的邮件      
    self.mail = self.msg.as_string()[:-1] + attach.as_string()
    
    return self.mail

if __name__ == &#39;__main__&#39;:
  mc = MailCreator()
  header = {&#39;from&#39;: &#39;zhaowei@163.com&#39;, &#39;to&#39;:&#39;weizhao@163.com&#39;, &#39;subject&#39;:&#39;我的一个测试邮件&#39;}
  data = [&#39;plain text information&#39;, &#39;<font color="red">html text information</font>&#39;]
  if sys.platform == &#39;win32&#39;:
    attach = [&#39;c:/windows/clock.avi&#39;]
  else:
    attach = [&#39;/bin/cp&#39;]
  
  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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software