Python中的电子邮件的收发使用smtplib和imaplib模块
作者:野牛程序员:2023-12-27 14:16:40python阅读 2970
使用smtplib和imaplib模块可以在Python中实现电子邮件的发送和接收。以下是发送和接收电子邮件的基本示例代码:
发送电子邮件:
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # 邮件配置 sender_email = "your_email@gmail.com" receiver_email = "recipient_email@gmail.com" subject = "Test Email" body = "This is a test email from Python." # 构建邮件 message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject message.attach(MIMEText(body, "plain")) # 邮箱登录 smtp_server = "smtp.gmail.com" smtp_port = 587 username = "your_email@gmail.com" password = "your_email_password" with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(username, password) server.sendmail(sender_email, receiver_email, message.as_string())
接收电子邮件:
import imaplib
import email
from email.header import decode_header
# 邮箱配置
email_user = "your_email@gmail.com"
email_pass = "your_email_password"
mail_server = "imap.gmail.com"
# 连接到邮箱
mail = imaplib.IMAP4_SSL(mail_server)
mail.login(email_user, email_pass)
mail.select("inbox")
# 搜索邮件
status, messages = mail.search(None, "ALL")
mail_ids = messages[0].split()
# 遍历邮件
for mail_id in mail_ids:
_, msg_data = mail.fetch(mail_id, "(RFC822)")
raw_email = msg_data[0][1]
msg = email.message_from_bytes(raw_email)
# 获取发件人、主题等信息
from_ = msg.get("From")
subject, encoding = decode_header(msg.get("Subject"))[0]
if isinstance(subject, bytes):
subject = subject.decode(encoding or "utf-8")
# 打印邮件信息
print(f"From: {from_}\\nSubject: {subject}\\n")
# 如果邮件包含文本内容,可以通过以下方式获取
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True)
print(body.decode("utf-8"))
# 关闭邮箱连接
mail.logout()请注意,上述示例中使用的是 Gmail 邮箱的配置,如果使用其他邮件服务提供商,需要相应调整 SMTP 和 IMAP 服务器的地址以及端口号。此外,为了安全起见,请确保使用应用程序专用密码或者授权码进行登录,而不要直接使用邮箱账户的原始密码。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

