赞
踩
Python 提供了对 POP 和 IMAP 协议的支持,主要通过标准库中的 poplib
和 imaplib
模块来实现。这些模块允许你使用 Python 代码与 POP3 和 IMAP4 邮件服务器进行通信。
poplib
进行 POP3 操作poplib
模块用于与 POP3 服务器进行交互。以下是一个示例,展示如何使用 poplib
从邮件服务器获取邮件。
poplib
获取邮件import poplib from email import parser # 连接到POP3服务器 pop3_server = 'pop.example.com' pop3_user = 'your_email@example.com' pop3_password = 'your_password' server = poplib.POP3_SSL(pop3_server) server.user(pop3_user) server.pass_(pop3_password) # 获取邮件统计信息 num_messages = len(server.list()[1]) # 获取并解析最新的一封邮件 if num_messages > 0: response, lines, octets = server.retr(num_messages) msg_content = b'\r\n'.join(lines).decode('utf-8') msg = parser.Parser().parsestr(msg_content) print('Subject:', msg['subject']) print('From:', msg['from']) print('To:', msg['to']) print('Date:', msg['date']) print('Body:', msg.get_payload()) # 断开连接 server.quit()
imaplib
进行 IMAP 操作imaplib
模块用于与 IMAP 服务器进行交互。以下是一个示例,展示如何使用 imaplib
从邮件服务器获取邮件。
imaplib
获取邮件import imaplib import email from email.header import decode_header # 连接到IMAP服务器 imap_server = 'imap.example.com' imap_user = 'your_email@example.com' imap_password = 'your_password' mail = imaplib.IMAP4_SSL(imap_server) mail.login(imap_user, imap_password) # 选择邮箱 mail.select("inbox") # 搜索邮件 status, messages = mail.search(None, 'ALL') mail_ids = messages[0].split() # 获取最新的一封邮件 if mail_ids: latest_email_id = mail_ids[-1] status, msg_data = mail.fetch(latest_email_id, '(RFC822)') for response_part in msg_data: if isinstance(response_part, tuple): msg = email.message_from_bytes(response_part[1]) subject, encoding = decode_header(msg["Subject"])[0] if isinstance(subject, bytes): subject = subject.decode(encoding if encoding else 'utf-8') print("Subject:", subject) print("From:", msg.get("From")) print("To:", msg.get("To")) print("Date:", msg.get("Date")) if msg.is_multipart(): for part in msg.walk(): content_type = part.get_content_type() content_disposition = str(part.get("Content-Disposition")) if content_type == "text/plain" and "attachment" not in content_disposition: body = part.get_payload(decode=True).decode() print("Body:", body) break else: body = msg.get_payload(decode=True).decode() print("Body:", body) # 断开连接 mail.logout()
poplib
和 imaplib
特性 | poplib | imaplib |
---|---|---|
主要功能 | 下载邮件到本地,默认情况下从服务器删除 | 在服务器上管理和同步邮件 |
复杂度 | 简单,适用于基本邮件下载和读取 | 较复杂,适用于高级邮件管理和操作 |
支持的操作 | 下载、删除邮件 | 下载、搜索、标记、移动、删除邮件等 |
适用场景 | 单设备访问邮件,节省服务器存储空间 | 多设备同步邮件,保留服务器上的邮件 |
Python 提供了 poplib
和 imaplib
模块来支持 POP3 和 IMAP4 协议。poplib
适用于简单的邮件下载和读取操作,而 imaplib
则适用于需要在服务器上进行高级邮件管理和同步操作的场景。选择合适的模块取决于你的具体需求和使用场景。
Python 提供了 smtplib
模块来支持发送邮件的操作,而 poplib
和 imaplib
模块则主要用于接收邮件。smtplib
模块可以与 poplib
和 imaplib
配合使用来完成完整的电子邮件收发流程。以下是分别使用 poplib
和 imaplib
接收邮件,并使用 smtplib
发送邮件的示例。
poplib
接收邮件并发送邮件poplib
)import poplib from email import parser # 连接到POP3服务器 pop3_server = 'pop.example.com' pop3_user = 'your_email@example.com' pop3_password = 'your_password' server = poplib.POP3_SSL(pop3_server) server.user(pop3_user) server.pass_(pop3_password) # 获取邮件统计信息 num_messages = len(server.list()[1]) # 获取并解析最新的一封邮件 if num_messages > 0: response, lines, octets = server.retr(num_messages) msg_content = b'\r\n'.join(lines).decode('utf-8') msg = parser.Parser().parsestr(msg_content) print('Subject:', msg['subject']) print('From:', msg['from']) print('To:', msg['to']) print('Date:', msg['date']) print('Body:', msg.get_payload()) # 断开连接 server.quit()
smtplib
)import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText smtp_server = 'smtp.example.com' smtp_user = 'your_email@example.com' smtp_password = 'your_password' from_email = 'your_email@example.com' to_email = 'recipient@example.com' subject = 'Test Email' body = 'This is a test email.' # 创建邮件对象 msg = MIMEMultipart() msg['From'] = from_email msg['To'] = to_email msg['Subject'] = subject # 添加邮件内容 msg.attach(MIMEText(body, 'plain')) try: server = smtplib.SMTP_SSL(smtp_server, 465) server.login(smtp_user, smtp_password) server.sendmail(from_email, to_email, msg.as_string()) print('Email sent successfully!') except Exception as e: print(f'Failed to send email: {e}') finally: server.quit()
imaplib
接收邮件并发送邮件imaplib
)import imaplib import email from email.header import decode_header # 连接到IMAP服务器 imap_server = 'imap.example.com' imap_user = 'your_email@example.com' imap_password = 'your_password' mail = imaplib.IMAP4_SSL(imap_server) mail.login(imap_user, imap_password) # 选择邮箱 mail.select("inbox") # 搜索邮件 status, messages = mail.search(None, 'ALL') mail_ids = messages[0].split() # 获取最新的一封邮件 if mail_ids: latest_email_id = mail_ids[-1] status, msg_data = mail.fetch(latest_email_id, '(RFC822)') for response_part in msg_data: if isinstance(response_part, tuple): msg = email.message_from_bytes(response_part[1]) subject, encoding = decode_header(msg["Subject"])[0] if isinstance(subject, bytes): subject = subject.decode(encoding if encoding else 'utf-8') print("Subject:", subject) print("From:", msg.get("From")) print("To:", msg.get("To")) print("Date:", msg.get("Date")) if msg.is_multipart(): for part in msg.walk(): content_type = part.get_content_type() content_disposition = str(part.get("Content-Disposition")) if content_type == "text/plain" and "attachment" not in content_disposition: body = part.get_payload(decode=True).decode() print("Body:", body) break else: body = msg.get_payload(decode=True).decode() print("Body:", body) # 断开连接 mail.logout()
smtplib
)import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText smtp_server = 'smtp.example.com' smtp_user = 'your_email@example.com' smtp_password = 'your_password' from_email = 'your_email@example.com' to_email = 'recipient@example.com' subject = 'Test Email' body = 'This is a test email.' # 创建邮件对象 msg = MIMEMultipart() msg['From'] = from_email msg['To'] = to_email msg['Subject'] = subject # 添加邮件内容 msg.attach(MIMEText(body, 'plain')) try: server = smtplib.SMTP_SSL(smtp_server, 465) server.login(smtp_user, smtp_password) server.sendmail(from_email, to_email, msg.as_string()) print('Email sent successfully!') except Exception as e: print(f'Failed to send email: {e}') finally: server.quit()
poplib
模块接收邮件。imaplib
模块接收邮件。smtplib
模块进行操作。通过这些示例代码,你可以在 Python 中实现邮件的接收和发送功能,结合 poplib
或 imaplib
进行接收,并使用 smtplib
进行发送。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。