国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1. SMTP (Simple Mail Transfer Protocol)
1. Construct an email: email.mime type
2. Create SMTP object
3. The Python SMTP object uses the sendmail method to send emails
2. Example
2: The service that supports SMTP has been installed on this machine
2. Using a third-party SMTP service
3、使用Python發(fā)送HTML格式的郵件
4、Python 發(fā)送帶附件的郵件
5、在 HTML 文本中添加圖片
6、同時支持HTML和Plain格式
7、加密SMTP
三、使用poplib接收郵件
第一步:使用poplib.POP3 或 poplib.POP3_SSL 按 POP3 協(xié)議把郵件的原始文本下載到本地;
第二步:使用 email.parser.Parser或BytesParser 解析郵件內(nèi)容為消息對象,然后,用適當?shù)男问桨燕]件內(nèi)容展示給用戶即可。
1、使用 email.parser.Parser解析郵件內(nèi)容為 email.message.Message(過時,不推薦)
2、使用email.parser.BytesParser 解析成email.message.EmailMessage對象
四、利用imaplib讀取郵件文本內(nèi)容及附件內(nèi)容
Home Backend Development Python Tutorial How to use email, smtplib, poplib, imaplib modules to send and receive emails in Python

How to use email, smtplib, poplib, imaplib modules to send and receive emails in Python

May 16, 2023 pm 11:44 PM
python email smtplib

The journey of an email is:

  • Mail User Agent (MUA) refers to an email client or software used by a user to access their email account. (i.e. email software similar to Outlook)

  • MTA: Mail Transfer Agent--Mail transfer agent is those Email service providers, such as NetEase, Sina, etc.

  • MDA: Mail Delivery Agent——Mail delivery agent. A server of the Email service provider

Sender-> MUA -> MTA -> MTA -> Several MTA -> MDA <- MUA < ;- The recipient

needs to write a program to send and receive emails, which is essentially:

  • Write a MUA to send the email to the MTA;

  • Write MUA to receive emails from MDA.

When sending emails, the protocol used by the MUA and MTA is SMTP: Simple Mail Transfer Protocol. The subsequent MTA also uses the SMTP protocol to another MTA.

When receiving emails, MUA and MDA use two protocols: POP: Post Office Protocol, the current version is 3, commonly known as POP3; IMAP: Internet Message Access Protocol, the current version is 4, the advantage is that not only can Mail, you can also directly operate the mail stored on the MDA, such as moving it from the inbox to the trash, etc.

1. SMTP (Simple Mail Transfer Protocol)

is the Simple Mail Transfer Protocol. It is a set of rules for transmitting mail from the source address to the destination address. It controls the delivery of letters. transit mode.

Python's smtplib provides a very convenient way to send emails. It simply encapsulates the SMTP protocol.

Python supports SMTP with two modules: smtplib and email. email is responsible for constructing emails, and smtplib is responsible for sending. mail.

1. Construct an email: email.mime type

Constructing an email object is a Messag object. If you construct a MIMEText object, it means A text mail object, if you construct a MIMEImage object, it represents a picture as an attachment. To combine multiple objects, use the MIMEMultipart object, and MIMEBasecan represent any object. Their inheritance relationship is as follows:

Message
+- MIMEBase
   +- MIMEMultipart
   +- MIMENonMultipart
      +- MIMEMessage
      +- MIMEText
      +- MIMEImage

First, we construct the simplest plain text email, and then send it through SMTP.

from email.mime.text import MIMEText
msg = MIMEText(&#39;hello, send by Python...&#39;, &#39;plain&#39;, &#39;utf-8&#39;)

Notice that when constructing the MIMEText object, the first parameter is the email body, the second parameter is the subtype of MIME, pass in 'plain', and finally The MIME is 'text/plain', and finally you must use utf-8 encoding to ensure multi-language compatibility.

2. Create SMTP object

The syntax is as follows:

import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

Parameter description:

  • host: SMTP server host. This parameter is optional. You can specify the IP address or domain name of the host as needed, for example: runoob.com.

  • port: If you provide the host parameter, you need to specify the port number used by the SMTP service. Generally, the SMTP port number is 25.

  • local_hostname: If SMTP is on your local machine, you only need to specify the server address as localhost.

3. The Python SMTP object uses the sendmail method to send emails

The syntax is as follows:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

Parameter description:

  • from_addr: Email sender address.

  • to_addrs: string list, email sending address.

  • msg: Send a message

Pay attention to the third parameter here, msg is a string, representing an email. To send an email, you must pay attention to the format of the information, because the email usually includes a title, sender, recipient, email content, attachments, etc. This format is the format defined in the smtp protocol.

2. Example

2: The service that supports SMTP has been installed on this machine

The following execution example requires that you have installed the service that supports SMTP on your machine.

sendmail()The method is to send an email. Since it can be sent to multiple people at one time, a list is passed in, and the email body is a str, as_string()turns the MIMEText object into str.

The text encoded by the Header object contains UTF-8 encoding information and Base64 encoded text.

The following is a simple example of using Python to send emails:

import smtplib
from email.mime.text import MIMEText
from email.header import Header
 
sender = &#39;from@runoob.com&#39;
receivers = [&#39;429240967@qq.com&#39;]  # 接收郵件,可設(shè)置為你的QQ郵箱或者其他郵箱
 
# 三個參數(shù):第一個為文本內(nèi)容,第二個 plain 設(shè)置文本格式,第三個 utf-8 設(shè)置編碼
message = MIMEText(&#39;Python 郵件發(fā)送測試內(nèi)容...&#39;, &#39;plain&#39;, &#39;utf-8&#39;)
message[&#39;From&#39;] = Header("菜鳥教程", &#39;utf-8&#39;)   # 發(fā)送者
message[&#39;To&#39;] =  Header("測試", &#39;utf-8&#39;)        # 接收者
message[&#39;Subject&#39;] = Header(&#39;Python SMTP 郵件測試主題&#39;, &#39;utf-8&#39;)
 
try:
    smtpObj = smtplib.SMTP(&#39;localhost&#39;)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "郵件發(fā)送成功"
except smtplib.SMTPException:
    print "Error: 無法發(fā)送郵件"

2. Using a third-party SMTP service

If we do not have sendmail access locally, we can also use other emails SMTP access from service providers (QQ, NetEase, Google, etc.).

login()Method used to log in to the SMTP server

The recipient's name is not displayed as a friendly name, such as Mr Green ;

Use the formataddr method to format an email address. If it contains Chinese, it needs to be encoded through the Header object.

msg['To'] receives a string instead of a list. If there are multiple email addresses, just use , to separate them.

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

# 第三方 SMTP 服務(wù)
mail_host = "mail.sss.com"  # 設(shè)置服務(wù)器
mail_user = "it_system@sss.com"  # 用戶名
mail_pass = "Ssss201709#"  # 口令

sender = &#39;it_system@tcl.com&#39;
receivers = &#39;sss.yang@tcsssl.com&#39;  # 接收郵件,可設(shè)置為你的QQ郵箱或者其他郵箱

message = MIMEText(&#39;Python 郵件內(nèi)容測試...&#39;, &#39;plain&#39;, &#39;utf-8&#39;)
message[&#39;From&#39;] = formataddr((&#39;SCBC-啊iT&#39;,   sender))
message[&#39;To&#39;] = formataddr((&#39;楊生&#39;, receivers))
message[&#39;Subject&#39;] = &#39;Python SMTP 郵件測試&#39;

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 為 SMTP 端口號
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("郵件發(fā)送成功")
except smtplib.SMTPException:
    print("Error: 無法發(fā)送郵件")

3、使用Python發(fā)送HTML格式的郵件

Python在構(gòu)造MIMEText對象時,把HTML字符串傳進去,再把第二個參數(shù)由plain變?yōu)?code>html就可以了:

具體代碼如下:

mail_msg = """
Python 郵件內(nèi)容測試...


這是一個鏈接


"""
message = MIMEText(mail_msg, &#39;html&#39;, &#39;utf-8&#39;)

4、Python 發(fā)送帶附件的郵件

帶附件的郵件可以看做包含若干部分的郵件:文本和各個附件本身,所以,可以構(gòu)造一個MIMEMultipart對象代表郵件本身,然后往里面加上一個MIMEText作為郵件正文,再繼續(xù)往里面加上表示附件的MIMEBase對象即可。

發(fā)送帶附件的郵件,首先要創(chuàng)建MIMEMultipart()實例,然后構(gòu)造附件,如果有多個附件,可依次構(gòu)造,最后利用smtplib.smtp發(fā)送。

from email.mime.multipart import MIMEMultipart

# 創(chuàng)建一個帶附件的實例
message = MIMEMultipart()

message[&#39;From&#39;] = formataddr((&#39;SCBC-啊iT&#39;, sender))
message[&#39;To&#39;] = formataddr((&#39;楊生&#39;, receivers))
message[&#39;Subject&#39;] = &#39;Python SMTP 郵件測試&#39;

mail_msg = """
Python 郵件內(nèi)容測試...


這是一個鏈接


"""
# 郵件正文內(nèi)容
message.attach(MIMEText(mail_msg, &#39;html&#39;, &#39;utf-8&#39;))

# 構(gòu)造附件1,傳送當前目錄下的 test.txt 文件
att = MIMEText(open(&#39;32.txt&#39;, &#39;rb&#39;).read(), &#39;base64&#39;, &#39;utf-8&#39;)
att["Content-Type"] = &#39;application/octet-stream&#39;
# 這里的filename可以任意寫,寫什么名字,郵件中顯示什么名字
att["Content-Disposition"] = &#39;attachment; filename="32.txt"&#39;
message.attach(att)

5、在 HTML 文本中添加圖片

要把圖片嵌入到郵件正文中,我們只需按照發(fā)送附件的方式,先把郵件作為附件添加進去,然后,在HTML中通過引用src="cid:0"就可以把附件作為圖片嵌入了。如果有多個圖片,給它們依次編號,然后引用不同的cid:x即可。

郵件的 HTML 文本中一般郵件服務(wù)商添加外鏈是無效的,正確添加圖片的實例如下所示:

from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

# 創(chuàng)建一個帶附件的實例
message = MIMEMultipart()

message[&#39;From&#39;] = formataddr((&#39;SCBC-啊iT&#39;, sender))
message[&#39;To&#39;] = formataddr((&#39;楊生&#39;, receivers))
message[&#39;Subject&#39;] = &#39;Python SMTP 郵件測試&#39;

mail_msg = """
Python 郵件內(nèi)容測試...


這是一個鏈接


圖片演示:





"""
# 郵件正文內(nèi)容
message.attach(MIMEText(mail_msg, &#39;html&#39;, &#39;utf-8&#39;))

# 指定圖片為當前目錄
with  open(&#39;a.jpg&#39;, &#39;rb&#39;) as fp:
    msgImage = MIMEImage(fp.read())

# 定義圖片 ID,在 HTML 文本中引用
msgImage.add_header(&#39;Content-ID&#39;, &#39;&#39;)
message.attach(msgImage)

或者通過MIMEBase來添加圖片

# 指定圖片為當前目錄
with  open(&#39;a.jpg&#39;, &#39;rb&#39;) as fp:
    # 設(shè)置附件的MIME和文件名,這里是png類型:
    mime = MIMEBase(&#39;image&#39;, &#39;jpg&#39;, filename=&#39;a.jpg&#39;)
    # 加上必要的頭信息:
    mime.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename=&#39;附件顯示名稱.jpg&#39;)
    mime.add_header(&#39;Content-ID&#39;, &#39;&#39;)  # 如果有多個文件需要使用.format(index)
    mime.add_header(&#39;X-Attachment-Id&#39;, &#39;0&#39;)  # 如果有多個文件需要使用.format(index)
    # 把附件的內(nèi)容讀進來:
    mime.set_payload(fp.read())
    # 用Base64編碼:
    encoders.encode_base64(mime)
    # 添加到MIMEMultipart:
    message.attach(mime)

6、同時支持HTML和Plain格式

如果我們發(fā)送HTML郵件,收件人通過瀏覽器或者Outlook之類的軟件是可以正常瀏覽郵件內(nèi)容的,但是,如果收件人使用的設(shè)備太古老,查看不了HTML郵件怎么辦?

辦法是在發(fā)送HTML的同時再附加一個純文本,如果收件人無法查看HTML格式的郵件,就可以自動降級查看純文本郵件。

利用MIMEMultipart就可以組合一個HTML和Plain,要注意指定subtype是alternative

msg = MIMEMultipart(&#39;alternative&#39;)
msg[&#39;From&#39;] = ...
msg[&#39;To&#39;] = ...
msg[&#39;Subject&#39;] = ...

msg.attach(MIMEText(&#39;hello&#39;, &#39;plain&#39;, &#39;utf-8&#39;))
msg.attach(MIMEText(&#39;Hello&#39;, &#39;html&#39;, &#39;utf-8&#39;))
# 正常發(fā)送msg對象...

7、加密SMTP

如果使用標準的25端口連接SMTP服務(wù)器發(fā)送郵件,即使身份驗證成功,因為明文傳輸?shù)木壒?,整個郵件發(fā)送過程都有可能被竊聽。要更安全地發(fā)送郵件,可以加密SMTP會話,實際上就是先創(chuàng)建SSL安全連接,然后再使用SMTP協(xié)議發(fā)送郵件。

在某些郵件服務(wù)提供商(例如Gmail)中,SMTP服務(wù)必須使用加密傳輸。我們來看看如何通過Gmail提供的安全SMTP發(fā)送郵件。

只需要在創(chuàng)建SMTP對象后,立刻調(diào)用starttls()方法,就創(chuàng)建了安全連接。后面的代碼和前面的發(fā)送郵件代碼完全一樣。

必須知道,Gmail的SMTP端口是587,因此,修改代碼如下:

smtp_server = &#39;smtp.gmail.com&#39;
smtp_port = 587
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
# 剩下的代碼和前面的一模一樣:
server.set_debuglevel(1)

三、使用poplib接收郵件

收取郵件就是編寫一個MUA作為客戶端,從MDA把郵件獲取到用戶的電腦或者手機上。收取郵件最常用的協(xié)議是POP協(xié)議,目前版本號是3,俗稱POP3。

Python內(nèi)置一個poplib模塊,實現(xiàn)了POP3協(xié)議,可以直接用來收郵件。

POP3 的命令和響應(yīng)數(shù)據(jù)都是基于 ASCII 文本的,并以 CR 和 LF(/r/n) 作為行結(jié)束符,響應(yīng)數(shù)據(jù)包括一個表示返回狀態(tài)的符號(+/)和描述信息。

請求和響應(yīng)的標準格式如下:

請求標準格式:命令 [參數(shù)] CRLF
響應(yīng)標準格式:+OK /[-ERR] description CRLF

POP3 協(xié)議客戶端的命令和服務(wù)器端對應(yīng)的響應(yīng)數(shù)據(jù)如下:

  • user name:向 POP 服務(wù)器發(fā)送登錄的用戶名。

  • pass string:向 POP 服務(wù)器發(fā)送登錄的密碼。

  • quit:退出 POP 服務(wù)器。

  • stat:統(tǒng)計郵件服務(wù)器狀態(tài),包括郵件數(shù)和總大小。

  • list [msg_no]:列出全部郵件或指定郵件。返回郵件編號和對應(yīng)大小。

  • retr msg_no:獲取指定郵件的內(nèi)容(根據(jù)郵件編號來獲取,編號從 1 開始)。

  • dele msg_no:刪除指定郵件(根據(jù)郵件編號來刪除,編號從 1 開始)。

  • noop:空操作。僅用于與服務(wù)器保持連接。

  • rset:用于撤銷 dele 命令。

poplib 模塊完全模擬了上面命令,poplib.POP3 或 poplib.POP3_SSL 為上面命令提供了相應(yīng)的方法,開發(fā)者只要依次使用上面命令即可從服務(wù)器端下載對應(yīng)的郵件

注意到POP3協(xié)議收取的不是一個已經(jīng)可以閱讀的郵件本身,而是郵件的原始文本,這和SMTP協(xié)議很像,SMTP發(fā)送的也是經(jīng)過編碼后的一大段文本。

要把POP3收取的文本變成可以閱讀的郵件,還需要用email模塊提供的各種類來解析原始文本,變成可閱讀的郵件對象。

所以,收取郵件分兩步:

第一步:使用poplib.POP3 或 poplib.POP3_SSL 按 POP3 協(xié)議把郵件的原始文本下載到本地;

用POP3獲取郵件其實很簡單,要獲取所有郵件,只需要循環(huán)使用retr()把每一封郵件內(nèi)容拿到即可。真正麻煩的是把郵件的原始內(nèi)容解析為可以閱讀的郵件對象。

import poplib
from email.parser import Parser
# email.parser 解析電子郵件,返回這個對象的email.message.Message實例
from email.header import decode_header
from email.utils import parseaddr

# 服務(wù)器及用戶信息
host = &#39;mail.tcl.com&#39;
username = &#39;bobin.yang@tcl.com&#39;
password = &#39;Ybb7654321&#39;

# 連接到POP3服務(wù)器
conn = poplib.POP3_SSL(host)
# 注意qq郵箱使用SSL連接
# 設(shè)置調(diào)試模式,可以看到與服務(wù)器的交互信息
conn.set_debuglevel(1)

# 打印POP3服務(wù)器的歡迎文字
print(conn.getwelcome().decode("utf-8"))

# 身份認證
conn.user(username)
conn.pass_(password)

# 獲取服務(wù)器上信件信息,返回一個列表,第一項是一共有多少封郵件,第二項是共有多少字節(jié)
# stat()返回郵件數(shù)量和占用空間
mail_total, total_size = conn.stat()
print(&#39;message: %s.Size:%s&#39; % (mail_total, total_size))

# list()返回(response, [&#39;mesg_num octets&#39;, ...], octets),第二項是編號
resp, mails, octets = conn.list()
print(mails)
# 返回的列表類似[b&#39;1 82923&#39;, b&#39;2 2184&#39;, ...]

# 獲取最新一封郵件,注意索引號從1開始
# POP3.retr(which) 檢索序號which的這個郵件,然后設(shè)置他的出現(xiàn)標志 返回(response, [&#39;line&#39;, ...], octets)這個三元組
resp, lines, ocetes = conn.retr(len(mails))
print(&#39;lines:&#39;, len(lines))
# lines 存儲了郵件的原始文本的每一行
# 可以獲得整個郵件的原始文本
print("-------------------")

第二步:使用 email.parser.Parser或BytesParser 解析郵件內(nèi)容為消息對象,然后,用適當?shù)男问桨燕]件內(nèi)容展示給用戶即可。

解析郵件的過程和上一節(jié)構(gòu)造郵件正好相反。

程序在創(chuàng)建 BytesParser(解析字節(jié)串格式的郵件數(shù)據(jù))或 Parser(解析字符串格式的郵件數(shù)據(jù))時,必須指定 policy=default;否則,BytesParse 或 Parser 解析郵件數(shù)據(jù)得到的就是過時的 Message 對象,,不是新的 EmailMessage,處理起來非常不方便。

1、使用 email.parser.Parser解析郵件內(nèi)容為 email.message.Message(過時,不推薦)
msg = b&#39;\r\n&#39;.join(lines).decode(&#39;utf-8&#39;)
# 解析出郵件
msg = Parser().parsestr(msg)


# email.Parser.parsestr(text, headersonly=False)
# 與parser()方法類似,不同的是他接受一個字符串對象而不是一個類似文件的對象
# 可選的headersonly表示是否在解析玩標題后停止解析,默認為否
# 返回根消息對象

# 編碼處理,文本郵件的內(nèi)容也是str,還需要檢測編碼,否則,非UTF-8編碼的郵件都無法正常顯示
def guess_charset(msg):
    charset = msg.get_charset()  # 從msg對象獲取編碼
    if charset is None:
        content_type = msg.get(&#39;Content-Type&#39;, &#39;&#39;).lower()  # 如果獲取不到,再從content—type字段獲取
        if &#39;charset&#39; in content_type:
            charset = content_type.split(&#39;charset=&#39;)[1].strip()
            return charset
    return charset


# 數(shù)據(jù)解碼,郵件的Subject或者Email中包含的名字都是經(jīng)過編碼后的str,要正常顯示,就必須decode
def decode_str(s):
    value, charset = decode_header(s)[0]  # 數(shù)據(jù),數(shù)據(jù)編碼方式,from email.header import decode_header
    # decode_header()返回一個list,因為像Cc、Bcc這樣的字段可能包含多個郵件地址,所以解析出來的會有多個元素。上面的代碼我們偷了個懶,只取了第一個元素。
    if charset:
        value = value.decode(charset)
    return value


# print_ingo函數(shù):解析郵件與構(gòu)造郵件的步驟正好相反
def print_info(msg, indent=0):  # indent用于縮進顯示
    if indent == 0:
        for header in [&#39;From&#39;, &#39;To&#39;, &#39;Subject&#39;]:  # 郵件的from、to、subject存在于根對象上
            value = msg.get(header, &#39;&#39;)
            if value:
                if header == &#39;Subject&#39;:
                    value = decode_str(value)  # 需要解碼subject字符串
                else:
                    # 解碼mail地址
                    hdr, addr = parseaddr(value)
                    name = decode_str(hdr)
                    value = &#39;%s&#39; % addr
            print(&#39;%s:  %s  %s&#39; % (header, value, name))
            print(&#39;-*-&#39; * 20)
    if msg.is_multipart():
        # 如果郵件對象是一個is_multipart,get_payload()返回一個list,包含所有子對象
        parts = msg.get_payload()  # 循環(huán)獲得列表項
        for n, part in enumerate(parts):
            # print(&#39;%spart %s&#39; % (&#39;  &#39; * indent, n))
            # print(&#39;%s------------&#39; % (&#39;  &#39; * indent))
            # 遞歸打印沒一個子對象
            print_info(part, indent + 1)
    else:
        # 郵件對象不是一個is_multipart,就根據(jù)content_type判斷
        content_type = msg.get_content_type()  # 數(shù)據(jù)類型
        if content_type == &#39;text/plain&#39; or content_type == &#39;text/html&#39;:  # 純文本 html文本
            # 純文本或html內(nèi)容
            content = msg.get_payload(decode=True)  # 獲得文本對象的字符串而非對象本身
            charset = guess_charset(msg)  # 要檢測文本編碼
            if charset: content = content.decode(charset)
            content = &#39;%s&#39; % (content)
            print(content)  # 獲取郵件文本內(nèi)容,如果只有文本,打印顯示的結(jié)果和郵件中看的效果一模一樣
        else:
            print(content_type+&#39;不是文本&#39;)


print_info(msg, 0)

# 退出
conn.quit()
2、使用email.parser.BytesParser 解析成email.message.EmailMessage對象

如果程序要獲取郵件的發(fā)件人、收件人和主題,直接通過 EmailMessage 的相應(yīng)屬性來獲取即可,與前面為 EmailMessage 設(shè)置發(fā)件人、收件人和主題的方式是對應(yīng)的。
如果程序要讀取 EmailMessage 的各部分,則需要調(diào)用該對象的 walk() 方法,該方法返回一個可迭代對象,程序使用 for 循環(huán)遍歷 walk() 方法的返回值,對郵件內(nèi)容進行逐項處理:

  • 如果郵件某項的 maintype 是 'multipart',則說明這一項是容器,用于包含郵件內(nèi)容、附件等其他項。

  • 如果郵件某項的 maintype 是 'text',則說明這一項的內(nèi)容是文本,通常就是郵件正文或文本附件。對于這種文本內(nèi)容,程序直接將其輸出到控制臺中。

  • 如果郵件中某個項的 maintype 屬性是“其他”,那么這一項的內(nèi)容就是作為附件的,程序會將附件內(nèi)容保存到本地文件中。

import os
import poplib
import mimetypes
from email.parser import Parser, BytesParser
from email.policy import default

msg_data = b&#39;\r\n&#39;.join(lines)
# 將字符串內(nèi)容解析成郵件,此處一定要指定policy=default
msg = BytesParser(policy=default).parsebytes(msg_data)
print(type(msg))

print(&#39;發(fā)件人:&#39; + msg[&#39;from&#39;])
print(&#39;收件人:&#39; + msg[&#39;to&#39;])
print(&#39;主題:&#39; + msg[&#39;subject&#39;])
print(&#39;第一個收件人名字:&#39; + msg[&#39;to&#39;].addresses[0].username)
print(&#39;第一個發(fā)件人名字:&#39; + msg[&#39;from&#39;].addresses[0].username)
for part in msg.walk():
    counter = 1
    # 如果maintype是multipart,說明是容器(用于包含正文、附件等)
    if part.get_content_maintype() == &#39;multipart&#39;:
        continue
    # 如果maintype是multipart,說明是郵件正文部分
    elif part.get_content_maintype() == &#39;text&#39;:
        print(part.get_content())
    # 處理附件
    else:
        # 獲取附件的文件名
        filename = part.get_filename()
        # 如果沒有文件名,程序要負責(zé)為附件生成文件名
        if not filename:
            # 根據(jù)附件的contnet_type來推測它的后綴名
            ext = mimetypes.guess_extension(part.get_content_type())
            # 如果推測不出后綴名
            if not ext:
                # 使用.bin作為后綴名
                ext = &#39;.bin&#39;
            # 程序為附件來生成文件名
            filename = &#39;part-%03d%s&#39; % (counter, ext)
        counter += 1
        # 將附件寫入的本地文件
        with open(os.path.join(&#39;.&#39;, filename), &#39;wb&#39;) as fp:
            fp.write(part.get_payload(decode=True))
# 退出服務(wù)器,相當于發(fā)送POP 3的quit命令
conn.quit()

四、利用imaplib讀取郵件文本內(nèi)容及附件內(nèi)容

通過IMAP協(xié)議來管理郵箱用的,稱作交互郵件訪問協(xié)議。

! encoding:utf8
&#39;&#39;&#39;
環(huán)境:
    Win10 64位 Python 2.7.5
參考:
    http://www.pythonclub.org/python-network-application/email-format
    http://blog.sina.com.cn/s/blog_4deeda2501016eyf.html
&#39;&#39;&#39;


import imaplib
import email


def parseHeader(message):
    """ 解析郵件首部 """
    subject = message.get(&#39;subject&#39;)  
    h = email.Header.Header(subject)
    dh = email.Header.decode_header(h)
    subject = unicode(dh[0][0], dh[0][1]).encode(&#39;gb2312&#39;)
    # 主題
    print subject
    print &#39;
&#39;
    # 發(fā)件人
    print &#39;From:&#39;, email.utils.parseaddr(message.get(&#39;from&#39;))[1]
    print &#39;
&#39;
    # 收件人
    print &#39;To:&#39;, email.utils.parseaddr(message.get(&#39;to&#39;))[1]
    print &#39;
&#39;
    # 抄送人
    print &#39;Cc:&#39;,email.utils.parseaddr(message.get_all(&#39;cc&#39;))[1]



def parseBody(message):
    """ 解析郵件/信體 """
    # 循環(huán)信件中的每一個mime的數(shù)據(jù)塊
    for part in message.walk():
        # 這里要判斷是否是multipart,是的話,里面的數(shù)據(jù)是一個message 列表
        if not part.is_multipart():
            charset = part.get_charset()
            # print &#39;charset: &#39;, charset
            contenttype = part.get_content_type()
            # print &#39;content-type&#39;, contenttype
            name = part.get_param("name") #如果是附件,這里就會取出附件的文件名
            if name:
                # 有附件
                # 下面的三行代碼只是為了解碼象=?gbk?Q?=CF=E0=C6=AC.rar?=這樣的文件名
                fh = email.Header.Header(name)
                fdh = email.Header.decode_header(fh)
                fname = dh[0][0]
                print &#39;附件名:&#39;, fname
                # attach_data = par.get_payload(decode=True) # 解碼出附件數(shù)據(jù),然后存儲到文件中

                # try:
                #     f = open(fname, &#39;wb&#39;) #注意一定要用wb來打開文件,因為附件一般都是二進制文件
                # except:
                #     print &#39;附件名有非法字符,自動換一個&#39;
                #     f = open(&#39;aaaa&#39;, &#39;wb&#39;)
                # f.write(attach_data)
                # f.close()
            else:
                #不是附件,是文本內(nèi)容
                print part.get_payload(decode=True) # 解碼出文本內(nèi)容,直接輸出來就可以了。
                # pass
            # print &#39;+&#39;*60 # 用來區(qū)別各個部分的輸出


def getMail(host, username, password, port=993):
    try:
        serv = imaplib.IMAP4_SSL(host, port)
    except Exception, e:
        serv = imaplib.IMAP4(host, port)

    serv.login(username, password)
    serv.select()
    # 搜索郵件內(nèi)容
    typ, data = serv.search(None, &#39;(FROM "xx@xxx.com")&#39;)

    count = 1
    pcount = 1
    for num in data[0].split()[::-1]:
        typ, data = serv.fetch(num, &#39;(RFC822)&#39;)
        text = data[0][1]
        message = email.message_from_string(text)   # 轉(zhuǎn)換為email.message對象
        parseHeader(message)
        print &#39;
&#39;
        parseBody(message)   
        pcount += 1
        if pcount > count:
            break

    serv.close()
    serv.logout()


if __name__ == &#39;__main__&#39;:
    host = "imap.mail_serv.com" # "pop.mail_serv.com"
    username = "Trevor@mail_serv.com"
    password = "your_password"
    getMail(host, username, password)

The above is the detailed content of How to use email, smtplib, poplib, imaplib modules to send and receive emails in Python. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

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)

Hot Topics

PHP Tutorial
1502
276
PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

python seaborn jointplot example python seaborn jointplot example Jul 26, 2025 am 08:11 AM

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

PHP integrated AI emotional computing technology PHP user feedback intelligent analysis PHP integrated AI emotional computing technology PHP user feedback intelligent analysis Jul 25, 2025 pm 06:54 PM

To integrate AI sentiment computing technology into PHP applications, the core is to use cloud services AIAPI (such as Google, AWS, and Azure) for sentiment analysis, send text through HTTP requests and parse returned JSON results, and store emotional data into the database, thereby realizing automated processing and data insights of user feedback. The specific steps include: 1. Select a suitable AI sentiment analysis API, considering accuracy, cost, language support and integration complexity; 2. Use Guzzle or curl to send requests, store sentiment scores, labels, and intensity information; 3. Build a visual dashboard to support priority sorting, trend analysis, product iteration direction and user segmentation; 4. Respond to technical challenges, such as API call restrictions and numbers

python list to string conversion example python list to string conversion example Jul 26, 2025 am 08:00 AM

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

python connect to sql server pyodbc example python connect to sql server pyodbc example Jul 30, 2025 am 02:53 AM

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

python pandas melt example python pandas melt example Jul 27, 2025 am 02:48 AM

pandas.melt() is used to convert wide format data into long format. The answer is to define new column names by specifying id_vars retain the identification column, value_vars select the column to be melted, var_name and value_name, 1.id_vars='Name' means that the Name column remains unchanged, 2.value_vars=['Math','English','Science'] specifies the column to be melted, 3.var_name='Subject' sets the new column name of the original column name, 4.value_name='Score' sets the new column name of the original value, and finally generates three columns including Name, Subject and Score.

Optimizing Python for Memory-Bound Operations Optimizing Python for Memory-Bound Operations Jul 28, 2025 am 03:22 AM

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

See all articles