授课语音

Python 邮件自动化


1. 什么是邮件自动化?

邮件自动化是指通过编程的方式自动化处理电子邮件的发送、接收和管理。常见的邮件自动化任务包括:

  • 自动发送邮件:例如,定期发送报告或提醒。
  • 自动接收邮件:例如,自动从邮箱中提取信息。
  • 自动处理邮件附件:例如,自动下载邮件附件并保存到指定目录。

Python 提供了丰富的库来支持邮件的自动化操作,常用的库包括:

  • smtplib:用于发送邮件。
  • email:用于构建和解析电子邮件。
  • imaplib:用于接收邮件。
  • schedule:用于定时任务(例如定时发送邮件)。

2. 发送邮件

Python 提供的 smtplib 库用于通过 SMTP 协议发送电子邮件。我们可以将邮件的内容、收件人、主题等信息组合在一起,然后通过 SMTP 服务器发送。

(1) 发送简单邮件

我们可以使用 smtplib.SMTP 类来连接邮件服务器,并通过 sendmail() 方法发送邮件。

代码示例

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 邮件服务器的地址和端口
smtp_server = "smtp.gmail.com"
smtp_port = 587

# 发件人和收件人
sender_email = "your_email@gmail.com"
receiver_email = "receiver_email@example.com"
password = "your_email_password"

# 邮件内容
subject = "自动化邮件"
body = "这是一个通过 Python 自动发送的邮件!"

# 创建 MIME 对象
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain"))

# 连接到 SMTP 服务器
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()  # 启动 TLS 加密
server.login(sender_email, password)

# 发送邮件
server.sendmail(sender_email, receiver_email, msg.as_string())

# 退出
server.quit()

print("邮件发送成功")

解释

  • MIMEText:用于邮件正文的内容。
  • MIMEMultipart:用于组合邮件的不同部分(例如,正文、附件)。
  • server.starttls():启动 TLS 加密,以确保安全的连接。
  • server.sendmail():实际发送邮件。

(2) 发送带附件的邮件

如果需要发送带附件的邮件,可以使用 MIMEBaseMIMEText 来将附件添加到邮件中。

代码示例

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

# 邮件服务器的地址和端口
smtp_server = "smtp.gmail.com"
smtp_port = 587

# 发件人和收件人
sender_email = "your_email@gmail.com"
receiver_email = "receiver_email@example.com"
password = "your_email_password"

# 邮件内容
subject = "邮件带附件"
body = "这是一个包含附件的自动化邮件!"

# 创建 MIME 对象
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain"))

# 附件路径
attachment = "example_file.txt"

# 打开附件并将其添加到邮件中
with open(attachment, "rb") as file:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(file.read())
    encoders.encode_base64(part)
    part.add_header("Content-Disposition", f"attachment; filename={attachment}")
    msg.attach(part)

# 连接到 SMTP 服务器
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()  # 启动 TLS 加密
server.login(sender_email, password)

# 发送邮件
server.sendmail(sender_email, receiver_email, msg.as_string())

# 退出
server.quit()

print("带附件的邮件发送成功")

解释

  • MIMEBase:用于处理附件的 MIME 类型。
  • encoders.encode_base64(part):对附件进行 Base64 编码。
  • part.add_header():为附件添加合适的 HTTP 头,指定文件名。

3. 定时发送邮件

我们可以结合 schedule 或者 APScheduler 来定期发送邮件。例如,设置每天发送一次报告。

(1) 使用 schedule 库定时发送邮件

import schedule
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 定义发送邮件的函数
def send_email():
    smtp_server = "smtp.gmail.com"
    smtp_port = 587
    sender_email = "your_email@gmail.com"
    receiver_email = "receiver_email@example.com"
    password = "your_email_password"
    subject = "自动发送的邮件"
    body = "这是一封定时发送的邮件!"
    
    msg = MIMEMultipart()
    msg["From"] = sender_email
    msg["To"] = receiver_email
    msg["Subject"] = subject
    msg.attach(MIMEText(body, "plain"))
    
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, msg.as_string())
    server.quit()

    print("定时邮件发送成功")

# 每天发送邮件
schedule.every().day.at("09:00").do(send_email)

while True:
    schedule.run_pending()
    time.sleep(1)

解释

  • schedule.every().day.at("09:00").do(send_email):指定每天的 9:00 自动发送邮件。

4. 接收邮件

Python 的 imaplib 库用于与 IMAP 邮件服务器交互,接收邮件。

(1) 使用 imaplib 获取未读邮件

import imaplib
import email
from email.header import decode_header

# 邮箱设置
imap_server = "imap.gmail.com"
username = "your_email@gmail.com"
password = "your_email_password"

# 连接到邮箱服务器
mail = imaplib.IMAP4_SSL(imap_server)
mail.login(username, password)

# 选择邮件箱(收件箱)
mail.select("inbox")

# 搜索未读邮件
status, messages = mail.search(None, "UNSEEN")

# 获取未读邮件的ID
email_ids = messages[0].split()

for email_id in email_ids:
    # 获取邮件数据
    status, msg_data = mail.fetch(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(f"主题: {subject}")

# 关闭连接
mail.close()
mail.logout()

解释

  • mail.search(None, "UNSEEN"):查找未读邮件。
  • msg["Subject"]:获取邮件的主题。

5. 总结

通过 Python 的 smtplibemailimaplib 等模块,我们可以轻松实现邮件的自动化处理,包括:

  • 自动发送简单邮件和带附件的邮件。
  • 定时发送邮件。
  • 接收和读取未读邮件。

这些功能可以用于自动报告、提醒、文件发送等场景,大大提高工作效率。

去1:1私密咨询

系列课程: