Python使用email?庫(kù)創(chuàng)建和解析電子郵件詳解
在現(xiàn)代軟件開(kāi)發(fā)中,處理電子郵件是一項(xiàng)常見(jiàn)的任務(wù)。無(wú)論是發(fā)送用戶注冊(cè)確認(rèn)郵件、重置密碼鏈接,還是自動(dòng)回復(fù)客戶咨詢,掌握如何使用Python生成和解析電子郵件都是非常有用的技能。本文將介紹如何使用Python的??email??庫(kù)來(lái)創(chuàng)建和解析電子郵件。
1. 環(huán)境準(zhǔn)備
首先,確保你的Python環(huán)境已經(jīng)安裝了??email??庫(kù)。該庫(kù)是Python標(biāo)準(zhǔn)庫(kù)的一部分,因此通常情況下你不需要額外安裝。如果你使用的是較老版本的Python,可能需要更新或安裝最新版本的Python。
2. 創(chuàng)建電子郵件
2.1 導(dǎo)入必要的模塊
from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header import smtplib
2.2 構(gòu)建郵件內(nèi)容
創(chuàng)建一個(gè)簡(jiǎn)單的純文本郵件:
def create_simple_email(sender, receiver, subject, body):
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = Header(sender)
msg['To'] = Header(receiver)
msg['Subject'] = Header(subject, 'utf-8')
return msg創(chuàng)建一個(gè)多部分郵件(包含HTML和附件):
def create_multipart_email(sender, receiver, subject, html_body, attachment_path=None):
msg = MIMEMultipart()
msg['From'] = Header(sender)
msg['To'] = Header(receiver)
msg['Subject'] = Header(subject, 'utf-8')
# 添加HTML正文
html_part = MIMEText(html_body, 'html', 'utf-8')
msg.attach(html_part)
# 如果有附件,添加附件
if attachment_path:
with open(attachment_path, 'rb') as file:
attachment = MIMEApplication(file.read(), _subtype="pdf")
attachment.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', 'report.pdf'))
msg.attach(attachment)
return msg2.3 發(fā)送郵件
使用SMTP協(xié)議發(fā)送郵件:
def send_email(smtp_server, smtp_port, sender, password, receiver, msg):
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # 啟用TLS加密
server.login(sender, password)
server.sendmail(sender, [receiver], msg.as_string())
server.quit()
print("郵件發(fā)送成功!")
except Exception as e:
print(f"郵件發(fā)送失敗: {e}")3. 解析電子郵件
3.1 導(dǎo)入解析所需的模塊
from email import policy from email.parser import BytesParser
3.2 解析郵件內(nèi)容
假設(shè)你從某個(gè)地方獲取到了原始郵件數(shù)據(jù)(例如,從郵箱服務(wù)器拉?。?,可以使用以下函數(shù)解析郵件:
def parse_email(raw_email_data):
msg = BytesParser(policy=policy.default).parsebytes(raw_email_data)
print("發(fā)件人:", msg['From'])
print("收件人:", msg['To'])
print("主題:", msg['Subject'])
if msg.is_multipart():
for part in msg.iter_parts():
content_type = part.get_content_type()
content_disposition = part.get("Content-Disposition")
if content_type == "text/plain" and 'attachment' not in content_disposition:
print("正文(純文本):", part.get_payload(decode=True).decode())
elif content_type == "text/html" and 'attachment' not in content_disposition:
print("正文(HTML):", part.get_payload(decode=True).decode())
elif 'attachment' in content_disposition:
print("附件:", part.get_filename())
else:
print("正文:", msg.get_payload(decode=True).decode())以上是一篇關(guān)于如何使用Python生成并解析電子郵件的技術(shù)博客文章,希望對(duì)你有所幫助。
4.方法補(bǔ)充
生成和解析電子郵件在許多實(shí)際應(yīng)用中都非常有用,比如自動(dòng)化郵件發(fā)送、郵件監(jiān)控系統(tǒng)等。下面我將分別展示如何使用Python來(lái)生成和解析電子郵件。
生成電子郵件
我們可以使用Python的??email??模塊來(lái)創(chuàng)建和發(fā)送電子郵件。以下是一個(gè)簡(jiǎn)單的示例,展示了如何生成一封包含文本內(nèi)容的電子郵件,并使用SMTP協(xié)議發(fā)送出去。
安裝必要的庫(kù)
首先,確保你已經(jīng)安裝了??email??和??smtplib??庫(kù)。這些庫(kù)通常在標(biāo)準(zhǔn)庫(kù)中,所以不需要額外安裝。
示例代碼
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 郵件發(fā)送者和接收者的郵箱地址
sender = 'your_email@example.com'
receiver = 'recipient_email@example.com'
# 創(chuàng)建一個(gè)MIME多部分消息對(duì)象
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = '測(cè)試郵件'
# 郵件正文
body = '這是一封測(cè)試郵件,由Python生成并發(fā)送。'
msg.attach(MIMEText(body, 'plain'))
# 連接到SMTP服務(wù)器并發(fā)送郵件
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_user = 'your_email@example.com'
smtp_password = 'your_password'
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # 啟用TLS加密
server.login(smtp_user, smtp_password)
text = msg.as_string()
server.sendmail(sender, receiver, text)
print('郵件發(fā)送成功!')
except Exception as e:
print(f'郵件發(fā)送失敗: {e}')
finally:
server.quit()解析電子郵件
解析電子郵件通常用于處理接收到的郵件內(nèi)容。我們可以使用??imaplib??庫(kù)來(lái)連接到IMAP服務(wù)器并獲取郵件,然后使用??email??模塊來(lái)解析郵件內(nèi)容。
安裝必要的庫(kù)
確保你已經(jīng)安裝了??imaplib??庫(kù)。這個(gè)庫(kù)也通常在標(biāo)準(zhǔn)庫(kù)中,所以不需要額外安裝。
示例代碼
import imaplib
import email
from email.header import decode_header
# IMAP服務(wù)器設(shè)置
imap_server = 'imap.example.com'
imap_user = 'your_email@example.com'
imap_password = 'your_password'
# 連接到IMAP服務(wù)器
try:
mail = imaplib.IMAP4_SSL(imap_server)
mail.login(imap_user, imap_password)
mail.select('inbox') # 選擇收件箱
# 搜索所有郵件
result, data = mail.search(None, 'ALL')
mail_ids = data[0].split()
# 獲取最新的一封郵件
if mail_ids:
latest_email_id = mail_ids[-1]
result, data = mail.fetch(latest_email_id, '(RFC822)')
raw_email = data[0][1]
# 解析郵件
msg = email.message_from_bytes(raw_email)
# 提取發(fā)件人、主題和正文
from_ = msg['From']
subject = msg['Subject']
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
try:
body = part.get_payload(decode=True).decode()
except:
pass
if content_type == "text/plain" and "attachment" not in content_disposition:
print(f'發(fā)件人: {from_}')
print(f'主題: {subject}')
print(f'正文: {body}')
else:
body = msg.get_payload(decode=True).decode()
print(f'發(fā)件人: {from_}')
print(f'主題: {subject}')
print(f'正文: {body}')
else:
print('沒(méi)有郵件')
except Exception as e:
print(f'郵件解析失敗: {e}')
finally:
mail.logout()這些代碼可以在實(shí)際應(yīng)用中進(jìn)行擴(kuò)展,以滿足更復(fù)雜的需求,比如處理附件、HTML格式的郵件等。
方法二:
在Python中生成和解析電子郵件可以使用標(biāo)準(zhǔn)庫(kù)中的??email???模塊,這個(gè)模塊提供了一組工具來(lái)處理電子郵件的創(chuàng)建、解析、修改和發(fā)送。下面我將詳細(xì)介紹如何使用??email??模塊來(lái)生成和解析電子郵件。
1. 生成電子郵件
首先,我們來(lái)看看如何使用??email??模塊生成一個(gè)簡(jiǎn)單的電子郵件。
安裝必要的庫(kù)
確保你的環(huán)境中安裝了Python的標(biāo)準(zhǔn)庫(kù),通常這些庫(kù)已經(jīng)包含在Python安裝包中,無(wú)需額外安裝。
創(chuàng)建郵件內(nèi)容
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# 創(chuàng)建一個(gè)MIME多部分消息對(duì)象
msg = MIMEMultipart()
# 設(shè)置發(fā)件人、收件人和主題
msg['From'] = Header("發(fā)件人姓名 <sender@example.com>")
msg['To'] = Header("收件人姓名 <receiver@example.com>")
msg['Subject'] = Header('這是一個(gè)測(cè)試郵件')
# 創(chuàng)建郵件正文
text = MIMEText('你好,這是一封測(cè)試郵件。', 'plain', 'utf-8')
msg.attach(text)
# 如果需要添加附件
# with open('path_to_file', 'rb') as f:
# attachment = MIMEApplication(f.read(), _subtype="pdf")
# attachment.add_header('Content-Disposition', 'attachment', filename=('gbk', '', 'filename.pdf'))
# msg.attach(attachment)發(fā)送郵件
要發(fā)送郵件,你可以使用??smtplib??庫(kù):
import smtplib
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_user = 'your_email@example.com'
smtp_password = 'your_password'
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # 啟用TLS加密
server.login(smtp_user, smtp_password)
server.sendmail(msg['From'], [msg['To']], msg.as_string())
print("郵件發(fā)送成功!")
except Exception as e:
print(f"郵件發(fā)送失敗: {e}")
finally:
server.quit()解析電子郵件
解析電子郵件通常涉及到從某個(gè)源(如文件或網(wǎng)絡(luò))讀取郵件內(nèi)容,并將其解析為可操作的對(duì)象。這里以從字符串解析郵件為例:
from email import policy
from email.parser import BytesParser
# 假設(shè)這是從某個(gè)地方獲取到的郵件原始數(shù)據(jù)
raw_email = b"""\
From: sender@example.com
To: receiver@example.com
Subject: 測(cè)試郵件
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
你好,這是一封測(cè)試郵件。
"""
# 使用BytesParser解析郵件
msg = BytesParser(policy=policy.default).parsebytes(raw_email)
# 訪問(wèn)郵件的不同部分
print("發(fā)件人:", msg['From'])
print("收件人:", msg['To'])
print("主題:", msg['Subject'])
print("正文:")
if msg.is_multipart():
for part in msg.iter_parts():
print(part.get_payload(decode=True))
else:
print(msg.get_payload(decode=True))通過(guò)這些步驟,你可以輕松地在Python中處理電子郵件相關(guān)的任務(wù)。如果你有更復(fù)雜的需求,比如處理HTML格式的郵件、添加多個(gè)附件等,??email??模塊也提供了相應(yīng)的支持。
到此這篇關(guān)于Python使用email?庫(kù)創(chuàng)建和解析電子郵件詳解的文章就介紹到這了,更多相關(guān)Python創(chuàng)建和解析郵件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
20行Python代碼實(shí)現(xiàn)一款永久免費(fèi)PDF編輯工具的實(shí)現(xiàn)
這篇文章主要介紹了20行Python代碼實(shí)現(xiàn)一款永久免費(fèi)PDF編輯工具的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
mvc框架打造筆記之wsgi協(xié)議的優(yōu)缺點(diǎn)以及接口實(shí)現(xiàn)
這篇文章主要給大家介紹了關(guān)于mvc框架打造筆記之wsgi協(xié)議的優(yōu)缺點(diǎn)以及接口實(shí)現(xiàn)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08
Python實(shí)現(xiàn)聚類(lèi)K-means算法詳解
這篇文章主要介紹了Python實(shí)現(xiàn)聚類(lèi)K-means算法詳解,K-means(K均值)算法是最簡(jiǎn)單的一種聚類(lèi)算法,它期望最小化平方誤差,具體詳解需要的朋友可以參考一下2022-07-07
關(guān)于Python ImportError: No module named&nb
最近多個(gè)小伙伴兒?jiǎn)枴癐mportError: No module named xxx“,應(yīng)該怎么樣解決,下面小編給大家?guī)?lái)了關(guān)于Python ImportError: No module named 通用解決方法,感興趣的朋友一起看看吧2022-11-11
Pandas?Groupby之在Python中匯總、聚合和分組數(shù)據(jù)的示例詳解
GroupBy是一個(gè)非常簡(jiǎn)單的概念,我們可以創(chuàng)建一個(gè)類(lèi)別分組,并對(duì)這些類(lèi)別應(yīng)用一個(gè)函數(shù),本文給大家介紹Pandas?Groupby之如何在Python中匯總、聚合和分組數(shù)據(jù),感興趣的朋友跟隨小編一起看看吧2023-07-07
Python中l(wèi)ambda的用法及其與def的區(qū)別解析
這篇文章主要介紹了Python中l(wèi)ambda的用法及其與def的區(qū)別解析,需要的朋友可以參考下2014-07-07
matplotlib如何設(shè)置坐標(biāo)軸刻度的個(gè)數(shù)及標(biāo)簽的方法總結(jié)
這里介紹兩種設(shè)置坐標(biāo)軸刻度的方法,一種是利用pyplot提交的api去進(jìn)行設(shè)置,另一種是通過(guò)調(diào)用面向?qū)ο蟮腶pi, 即通過(guò)matplotlib.axes.Axes去設(shè)置,需要的朋友可以參考下2021-06-06
Python輸出PowerPoint(ppt)文件中全部文字信息的方法
這篇文章主要介紹了Python輸出PowerPoint(ppt)文件中全部文字信息的方法,涉及Python通過(guò)windows中com組件操作ppt的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04

