Python的“email”模块:发送和接收电子邮件

B站影视 电影资讯 2025-03-24 08:14 2

摘要:例如,可以使用“EmailMessage”类创建新的电子邮件,并使用“send_message”函数通过SMTP发送它。下面的代码片段演示了如何发送简单的文本电子邮件:

Fuzzy

Python的“email”模块允许在Python脚本中发送和接收电子邮件。它提供了一个简单的接口来构造和解析电子邮件消息,并支持各种编码和解码方法。

要使用“email”模块,首先需要使用以下语句导入它:

导入后,可以使用“email”模块提供的各种类和函数来构造电子邮件消息,并使用简单邮件传输协议(smtp)发送它们。

例如,可以使用“EmailMessage”类创建新的电子邮件,并使用“send_message”函数通过SMTP发送它。下面的代码片段演示了如何发送简单的文本电子邮件:

import emailimport smtplib# Create a new email messagemessage = email.message.EmailMessage# Set the sender and recipientmessage['From'] = 'sender@example.com'message['To'] = 'recipient@example.com'# Set the subject and bodymessage['Subject'] = 'Hello from Python!'message.set_content('This is a test email sent using Python.')# Send the email using SMTPserver = smtplib.SMTP('smtp.example.com')server.send_message(message)server.quit

还可以使用“电子邮件”模块接收使用Internet邮件访问协议(IMAP)的电子邮件。为此,您可以使用“imaplib”模块,它是Python标准库的一部分。下面的代码片段演示了如何连接到IMAP服务器并获取邮箱名称列表:

import imaplib# Connect to the IMAP serverserver = imaplib.IMAP4_SSL('imap.example.com')# Authenticate using the username and passwordserver.login('username', 'password')# Fetch the list of mailbox namesresponse, mailbox_list = server.list# Print the list of mailbox namesprint(mailbox_list)# Disconnect from the serverserver.logout

总之,“email”模块是Python中发送和接收电子邮件消息的强大工具。它为构造和解析电子邮件消息提供了一个简单而灵活的接口,并广泛用于许多Python应用程序中。

来源:自由坦荡的湖泊AI

相关推荐