Home Backend Development PHP Problem Python mail processing example

Python mail processing example

Jul 06, 2021 pm 02:36 PM
python

Detailed explanation of Python basics is a very detailed code example for the email. Friends who are familiar with Python basics are very helpful. You can refer to the following

Python mail processing example

1. Sending emails

The Python standard library provides smtplib, which is used to implement the SMTP protocol to send emails. The standard library also provides the email module to help us build email formats. SMTP (Simple Mail Transfer Protocol) is a set of rules for transmitting mail from a source address to a destination address, which is used to control the transfer method of letters.

Get QQ mailbox password (authorization code)

2. Send an email in plain text format

The code is as follows:

import smtplib

from email.mime.text import MIMEText
from email.header import Header

# 邮箱用户名
sender = 'dad@qq.com'(输入你的邮箱)
# 邮箱密码(部分邮箱为授权码)
password = '123456'(输入你的密码)
# 收件人邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receiver = ['baby@qq.com', ](输入你要发送人的邮箱)
# 邮件正文
text = 'Hello,baby'
message = MIMEText(text, 'plain', 'utf-8')
# 发件人显式的名字
message['From'] = Header('拿头来坚持', 'utf-8')
# 收件人显式的名字
message['To'] = Header('baby', 'utf-8')
# 邮件标题
message['Subject'] = '爸爸来信,请接收!'

try:
    # 使用QQ企业邮箱服务器发送
    smtp = smtplib.SMTP('smtp.qq.com')
    # 登录
    smtp.login(sender, password)
    # 发送
    smtp.sendmail(sender, receiver, message.as_string())
    print('邮件发送成功!')
    # 退出服务器
    smtp.quit()
except smtplib.SMTPException as e:
    print('Error!邮件发送失败!', e)
Copy after login

Basic Analysis of Python Email Processing

Send emails in plain text format Execution results:

3. Send emails in HTML format

The code is as follows:

import smtplib

from email.mime.text import MIMEText
from email.header import Header

# 邮箱用户名
sender = 'dad@qq.com'(输入你的邮箱)
# 邮箱密码(部分邮箱为授权码)
password = '123456'(输入你的密码)
# 收件人邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receiver = ['baby@qq.com', ](输入你要发送人的邮箱)
# 邮件正文
msg = '''
    <p><a href=&#39;https://blog.csdn.net/weixin_46382560?spm=1011.2124.3001.5343&#39;>拿头来坚持</p>
          Life goes on, learning goes on
        </p> <!----></div></div> <div class="user-profile-head-info-b" data-v-d1dbb6f8><ul data-v-d1dbb6f8><li data-v-d1dbb6f8><div class="user-profile-statistics-num" data-v-d1dbb6f8>22,574</div> <div class="user-profile-statistics-name" data-v-d1dbb6f8>被访问量</div></li> <li data-v-d1dbb6f8><a href="javascript:;" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  data-v-d1dbb6f8><div class="user-profile-statistics-num" data-v-d1dbb6f8>24</div> <div class="user-profile-statistics-name" data-v-d1dbb6f8>原创文章</div></a></li> <li data-v-d1dbb6f8><a href="https://blog.csdn.net/rank/list/total" rel="external nofollow"  rel="external nofollow"  target="_blank" data-report-click="{&quot;spm&quot;:&quot;3001.5476&quot;}" data-report-query="spm=3001.5476" data-v-d1dbb6f8><div class="user-profile-statistics-num" data-v-d1dbb6f8>128,997</div> <div class="user-profile-statistics-name" data-v-d1dbb6f8>作者排名</div></a></li> <li data-v-d1dbb6f8><a href="javascript:;" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  data-v-d1dbb6f8><div class="user-profile-statistics-num" data-v-d1dbb6f8>762</div> <div class="user-profile-statistics-name" data-v-d1dbb6f8>粉丝数量</div></a></li></ul></div></div></div> <div class="user-profile-body" data-v-3f0fdf46 data-v-80922f46><div class="user-profile-body-inner" data-v-3f0fdf46><div class="user-profile-body-left" data-v-3f0fdf46><div class="user-profile-aside" data-v-d487ed78 data-v-3f0fdf46><div class="user-general-info single-general-info" data-v-d487ed78><ul data-v-d487ed78><!----> <!----> <li class="user-general-info-join-csdn" data-v-d487ed78><i data-v-d487ed78></i> <span data-v-d487ed78>于</span> <span class="user-general-info-key-word" data-v-d487ed78>2020-02-22</span> <span data-v-d487ed78>加入CSDN</span></li></ul></div> <!----> <div class="user-achievement user-profile-aside-common-box" data-v-d487ed78><div class="aside-common-box-head" data-v-d487ed78>获得成就</div> <div class="aside-common-box-bottom" data-v-d487ed78><div class="aside-common-box-content" data-v-d487ed78><ul data-v-d487ed78><li data-v-d487ed78>
        <i style="background-image: url(https://img-home.csdnimg.cn/images/20210114022819.png)"></i>
        <div>获得<span>212</span>次点赞</div>
      </li><li data-v-d487ed78>
        <i style="background-image: url(https://img-home.csdnimg.cn/images/20210114022831.png)"></i>
        <div>内容获得<span>111</span>次评论</div>
      </li><li data-v-d487ed78>
        <i style="background-image: url(https://img-home.csdnimg.cn/images/20210114022828.png)"></i>
        <div>获得<span>562</span>次收藏</div>
      &#39;&#39;&#39;
# 指定消息体使用HTML格式
message = MIMEText(msg, &#39;html&#39;, &#39;utf-8&#39;)
# 发件人显式的名字
message[&#39;From&#39;] = Header(&#39;拿头来坚持&#39;, &#39;utf-8&#39;)
# 收件人显式的名字
message[&#39;To&#39;] = Header(&#39;baby&#39;, &#39;utf-8&#39;)
# 邮件标题
message[&#39;Subject&#39;] = &#39;爸爸来信,请接收!&#39;

try:
    # 使用QQ企业邮箱服务器发送
    smtp = smtplib.SMTP(&#39;smtp.qq.com&#39;)
    # 登录
    smtp.login(sender, password)
    # 发送
    smtp.sendmail(sender, receiver, message.as_string())
    print(&#39;邮件发送成功!&#39;)
    # 退出服务器
    smtp.quit()
except smtplib.SMTPException as e:
    print(&#39;Error!邮件发送失败!&#39;, e)
Copy after login

Python basic analysis of email processing

Execution results of sending emails in HTML format:

4. Send emails with attachments

The code is as follows:

import smtplib

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

# 邮箱用户名
sender = &#39;dad@qq.com&#39;(输入你的邮箱)
# 邮箱密码(部分邮箱为授权码)
password = &#39;123456&#39;(输入你的密码)
# 收件人邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receiver = [&#39;baby@qq.com&#39;, ](输入你要发送人的邮箱)
# 指定消息体使用复合类型
message = MIMEMultipart()
# 发件人显式的名字
message[&#39;From&#39;] = Header(&#39;拿头来坚持&#39;, &#39;utf-8&#39;)
# 收件人显式的名字
message[&#39;To&#39;] = Header(&#39;baby&#39;, &#39;utf-8&#39;)
# 邮件标题
message[&#39;Subject&#39;] = &#39;爸爸来信,请接收!&#39;
# 邮件正文
msg = &#39;&#39;&#39;
    <p><a href=&#39;https://blog.csdn.net/weixin_46382560?spm=1011.2124.3001.5343&#39;>拿头来坚持</p>
          Life goes on, learning goes on
        </p> <!----></div></div> <div class="user-profile-head-info-b" data-v-d1dbb6f8><ul data-v-d1dbb6f8><li data-v-d1dbb6f8><div class="user-profile-statistics-num" data-v-d1dbb6f8>22,574</div> <div class="user-profile-statistics-name" data-v-d1dbb6f8>被访问量</div></li> <li data-v-d1dbb6f8><a href="javascript:;" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  data-v-d1dbb6f8><div class="user-profile-statistics-num" data-v-d1dbb6f8>24</div> <div class="user-profile-statistics-name" data-v-d1dbb6f8>原创文章</div></a></li> <li data-v-d1dbb6f8><a href="https://blog.csdn.net/rank/list/total" rel="external nofollow"  rel="external nofollow"  target="_blank" data-report-click="{&quot;spm&quot;:&quot;3001.5476&quot;}" data-report-query="spm=3001.5476" data-v-d1dbb6f8><div class="user-profile-statistics-num" data-v-d1dbb6f8>128,997</div> <div class="user-profile-statistics-name" data-v-d1dbb6f8>作者排名</div></a></li> <li data-v-d1dbb6f8><a href="javascript:;" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  data-v-d1dbb6f8><div class="user-profile-statistics-num" data-v-d1dbb6f8>762</div> <div class="user-profile-statistics-name" data-v-d1dbb6f8>粉丝数量</div></a></li></ul></div></div></div> <div class="user-profile-body" data-v-3f0fdf46 data-v-80922f46><div class="user-profile-body-inner" data-v-3f0fdf46><div class="user-profile-body-left" data-v-3f0fdf46><div class="user-profile-aside" data-v-d487ed78 data-v-3f0fdf46><div class="user-general-info single-general-info" data-v-d487ed78><ul data-v-d487ed78><!----> <!----> <li class="user-general-info-join-csdn" data-v-d487ed78><i data-v-d487ed78></i> <span data-v-d487ed78>于</span> <span class="user-general-info-key-word" data-v-d487ed78>2020-02-22</span> <span data-v-d487ed78>加入CSDN</span></li></ul></div> <!----> <div class="user-achievement user-profile-aside-common-box" data-v-d487ed78><div class="aside-common-box-head" data-v-d487ed78>获得成就</div> <div class="aside-common-box-bottom" data-v-d487ed78><div class="aside-common-box-content" data-v-d487ed78><ul data-v-d487ed78><li data-v-d487ed78>
        <i style="background-image: url(https://img-home.csdnimg.cn/images/20210114022819.png)"></i>
        <div>获得<span>212</span>次点赞</div>
      </li><li data-v-d487ed78>
        <i style="background-image: url(https://img-home.csdnimg.cn/images/20210114022831.png)"></i>
        <div>内容获得<span>111</span>次评论</div>
      </li><li data-v-d487ed78>
        <i style="background-image: url(https://img-home.csdnimg.cn/images/20210114022828.png)"></i>
        <div>获得<span>562</span>次收藏</div>
      &#39;&#39;&#39;
# 邮件附加html文件
message.attach(MIMEText(msg, &#39;html&#39;, &#39;utf-8&#39;))
# 添加附件
attached_file = MIMEText(open(__file__, encoding=&#39;utf-8&#39;).read(), &#39;base64&#39;, &#39;utf-8&#39;)
# 指定附件的文件名和原先的文件不一样
attached_file[&#39;Content-Disposition&#39;] = &#39;attachment;filename="mail.py"&#39;
# 邮件附加附件
message.attach(attached_file)
try:
    # 使用QQ企业邮箱服务器发送
    smtp = smtplib.SMTP(&#39;smtp.qq.com&#39;)
    # 登录
    smtp.login(sender, password)
    # 发送
    smtp.sendmail(sender, receiver, message.as_string())
    print(&#39;邮件发送成功!&#39;)
    # 退出服务器
    smtp.quit()
except smtplib.SMTPException as e:
    print(&#39;Error!邮件发送失败!&#39;, e)
Copy after login

Basic analysis of Python email processing

Send with attachments Attachment email execution result:

5. Send picture email

##The code is as follows:

import smtplib

from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.header import Header

# 邮箱用户名
sender = &#39;dad@qq.com&#39;(输入你的邮箱)
# 邮箱密码(部分邮箱为授权码)
password = &#39;123456&#39;(输入你的密码)
# 收件人邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receiver = [&#39;baby@qq.com&#39;, ](输入你要发送人的邮箱)
# 利用related定义内嵌资源的邮件体
message = MIMEMultipart(&#39;related&#39;)
# 发件人显式的名字
message[&#39;From&#39;] = Header(&#39;拿头来坚持&#39;, &#39;utf-8&#39;)
# 收件人显式的名字
message[&#39;To&#39;] = Header(&#39;baby&#39;, &#39;utf-8&#39;)
# 邮件标题
message[&#39;Subject&#39;] = &#39;爸爸来信,请接收!&#39;
# 邮件正文
content = MIMEMultipart(&#39;alternative&#39;)
# html内容
msg = &#39;&#39;&#39;
    <p><a href=&#39;https://blog.csdn.net/weixin_46382560?spm=1011.2124.3001.5343&#39;>拿头来坚持</p>
          Life goes on, learning goes on
    <p>
    拿头来坚持的个人主页
    <img src=&#39;cid:img01&#39;>
    </p>
      &#39;&#39;&#39;
# 邮件附加html文件
message.attach(MIMEText(msg, &#39;html&#39;, &#39;utf-8&#39;))
# 添加图片
with open(&#39;csdn.png&#39;, &#39;rb&#39;) as f:
    img01 = MIMEImage(f.read())
# 定义资源的名字为img01
img01.add_header(&#39;Content-ID&#39;, &#39;img01&#39;)
# 邮件附加图片
message.attach(img01)
try:
    # 使用QQ企业邮箱服务器发送
    smtp = smtplib.SMTP(&#39;smtp.qq.com&#39;)
    # 登录
    smtp.login(sender, password)
    # 发送
    smtp.sendmail(sender, receiver, message.as_string())
    print(&#39;邮件发送成功!&#39;)
    # 退出服务器
    smtp.quit()
except smtplib.SMTPException as e:
    print(&#39;Error!邮件发送失败!&#39;, e)
Copy after login

Python Basic analysis of email processing

Email execution results for sending pictures:

6. Receiving emails

There are two common ways to receive emails Protocols: POP3 and IMAP protocols

POP3 protocol (Post Office Protocol-Version3, Post Office Protocol Version 3): allows email clients to download emails on the server, but during client operations (such as moving emails, Mark as read, etc.) will not be fed back to the server. For example, if 3 emails from the mailbox are collected through the client and moved to other folders, these emails on the mail server will not be moved synchronously.

IMAP protocol (Internet Mail Access Protocol): Provides two-way communication between Webmail and email clients. Any changes made on the client will be synchronized to the server. If the mail is operated on the client, the mail on the server will also be operated accordingly.

7. Download emails using POP3 protocol

The code is as follows:

import poplib

from email.parser import Parser

# 登录邮箱的用户名
username = &#39;baby@qq.com&#39;(输入你的邮箱)
# 登录邮箱的密码(部分邮箱为授权码)
password = &#39;123456&#39;(输入你的密码)
# 连接邮箱服务器
pop_server = poplib.POP3(&#39;pop.qq.com&#39;)
# 打印出邮箱服务器的欢迎文字
print(pop_server.getwelcome())
# 登录邮箱服务器
pop_server.user(username)
pop_server.pass_(password)
# 打印出当前账号的状态,第一个返回值为邮件数,第二个返回值为占用空间
print(&#39;Server stat&#39;, pop_server.stat())
# 获取所以邮件列表
resp, mails, octets = pop_server.list()
print(mails)
# 获取最新的一封邮件(序列号最大的),邮件索引从1开始计数
index = len(mails)
resp, lines, octets = pop_server.retr(index)
content = b&#39;\r\n&#39;.join(lines).decode(&#39;utf-8&#39;)
# 解析出邮件
msg = Parser().parsestr(content)
# 可以根据邮件索引号直接从服务器删除邮件
# pop_server.dele(index)
# 关闭连接
pop_server.quit()
Copy after login
Basic Analysis of Python Email Processing

Execution result:

b' OK XMail POP3 Server v1.0 Service Ready(XMail v1.0)'

Server stat (15, 50814)
[b'1 1255', b'2 1286', b'3 1310', b'4 1398', b'5 1458', b'6 1450', b'7 1602', b'8 1633', b'9 5001', b' 10 2347', b'11 2371', b'12 2267', b'13 5033', b'14 5077', b'15 17326']

If the server is correctly connected and the number of emails is listed , indicating that we have used the POP3 protocol correctly.

This concludes this article about email processing with a detailed explanation of the basics of Python

Recommended learning:

php video tutorial

The above is the detailed content of Python mail processing example. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to view server version of Redis How to view server version of Redis Apr 10, 2025 pm 01:27 PM

Question: How to view the Redis server version? Use the command line tool redis-cli --version to view the version of the connected server. Use the INFO server command to view the server's internal version and need to parse and return information. In a cluster environment, check the version consistency of each node and can be automatically checked using scripts. Use scripts to automate viewing versions, such as connecting with Python scripts and printing version information.

How secure is Navicat's password? How secure is Navicat's password? Apr 08, 2025 pm 09:24 PM

Navicat's password security relies on the combination of symmetric encryption, password strength and security measures. Specific measures include: using SSL connections (provided that the database server supports and correctly configures the certificate), regularly updating Navicat, using more secure methods (such as SSH tunnels), restricting access rights, and most importantly, never record passwords.

See all articles