Python基础详解之邮件处理
简介
本篇文章主要介绍如何使用Python处理邮件,包括邮件的发送和接收,以及邮件的解析和处理。为了更好地理解,我们将分别从三个方面来阐述:
- 发送邮件
- 接收邮件
- 解析和处理邮件
发送邮件
发送邮件是指通过Python向收件人发送邮件的过程。Python中有多种发送邮件的方式,此处我们介绍使用smtplib库实现发送邮件。
示例1:使用smtplib发送邮件
import smtplib
from email.mime.text import MIMEText
from email.header import Header
smtp_server = 'smtp.qq.com'
sender = 'example@qq.com'
receiver = 'example@163.com'
subject = 'Python发送邮件示例'
body = '这是一封Python发送的邮件'
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = Header(sender, 'utf-8')
msg['To'] = Header(receiver, 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
smtpObj = smtplib.SMTP_SSL(smtp_server, 465)
smtpObj.login(sender, 'your_email_password')
smtpObj.sendmail(sender, [receiver], msg.as_string())
smtpObj.quit()
接收邮件
接收邮件是指通过Python从邮件服务器获取邮件的过程。Python中有许多库可以用于接收邮件,本文介绍使用poplib库。
示例2:使用poplib接收邮件
import poplib
from email.parser import Parser
pop3_server = 'pop.qq.com'
username = 'example@qq.com'
password = 'your_email_password'
server = poplib.POP3_SSL(pop3_server)
server.user(username)
server.pass_(password)
resp, mails, octets = server.list()
index = len(mails)
resp, lines, octets = server.retr(index)
msg_content = b'\r\n'.join(lines).decode('utf-8')
msg = Parser().parsestr(msg_content)
print(f'Subject: {msg["Subject"]}')
print(f'From: {msg["From"]}')
print(f'To: {msg["To"]}')
for part in msg.walk():
if not part.is_multipart():
body = part.get_payload(decode=True)
print(body.decode('utf-8'))
server.quit()
解析和处理邮件
当我们从邮件服务器获取到邮件时,我们可能需要对邮件进行一些处理,例如解析邮件内容、提取附件等。
示例3:解析邮件内容
import email
import os
mail_path = 'example.eml'
with open(mail_path, 'rb') as f:
lines = f.readlines()
msg_content = b''.join(lines).decode('utf-8')
msg = email.message_from_string(msg_content)
print(f'Subject: {msg["Subject"]}')
print(f'From: {msg["From"]}')
print(f'To: {msg["To"]}')
for part in msg.walk():
if not part.is_multipart():
body = part.get_payload(decode=True)
print(body.decode('utf-8'))
# 提取附件
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if not filename:
continue
if not os.path.exists('./attachment'):
os.makedirs('./attachment')
filepath = os.path.join('./attachment', filename)
with open(filepath, 'wb') as f:
f.write(part.get_payload(decode=True))
总结
至此,我们介绍了如何使用Python进行邮件处理。发送邮件使用smtplib库,接收邮件使用poplib库,邮件解析和处理则使用email库。希望本文能为大家解决邮件处理问题,也欢迎大家围观我的博客:www.example.com。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python基础详解之邮件处理 - Python技术站