使用Python发送邮件的详细指南与进阶用法

使用Python发送邮件的详细指南与进阶用法

在现代编程中,自动化任务是提高效率的重要手段之一。发送邮件是一项常见的任务,无论是用于通知、报警还是报告。本篇博客将详细介绍如何使用Python发送邮件,并介绍如何实现定时发送邮件的进阶用法。

前提条件

在开始之前,请确保你已经安装了必要的库:

pip install python-dotenv

一 基本实现

1. 环境配置

为了安全起见,不建议将敏感信息(如邮箱密码)硬编码在代码中。我们使用.env文件来存储这些信息,该文件置于脚本的同级目录:

.env文件内容:

SENDER_EMAIL=your_email@example.com
EMAIL_PASSWORD=your_email_password

注意:邮箱的密码并非你的登录密码,而是你的邮箱服务商提供的授权码,如qq邮箱,在qq邮箱网页端设置中获取授权码后,配置在.env

2. 邮件发送代码

以下是一个完整的邮件发送脚本(以qq邮箱为例):

import os
import smtplib
import logging
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 邮件发送者和接收者
sender_email = os.getenv("SENDER_EMAIL")
password = os.getenv("EMAIL_PASSWORD")
receiver_emails = ["receiver1@example.com", "receiver2@example.com", "receiver3@example.com"]

# 设置日志记录
logging.basicConfig(level=logging.INFO, filename='email_log.txt', filemode='a',
                    format='%(asctime)s - %(levelname)s - %(message)s')

def create_email(subject, sender_email, receiver_emails, text, html=''):
    """创建邮件对象和设置邮件内容"""
    message = MIMEMultipart("alternative")
    message["Subject"] = subject
    message["From"] = sender_email
    message["To"] = ', '.join(receiver_emails)
    
    part1 = MIMEText(text, "plain")
    part2 = MIMEText(html, "html")
    
    message.attach(part1)
    message.attach(part2)
    
    return message

def send_email(sender_email, password, receiver_emails, message):
    """发送邮件"""
    try:
        server = smtplib.SMTP_SSL("smtp.qq.com", 465)
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_emails, message.as_string())
        logging.info("邮件发送成功")
    except smtplib.SMTPAuthenticationError:
        logging.error("邮件发送失败: 认证错误")
    except smtplib.SMTPRecipientsRefused:
        logging.error("邮件发送失败: 收件人被拒绝")
    except smtplib.SMTPSenderRefused:
        logging.error("邮件发送失败: 发件人被拒绝")
    except smtplib.SMTPException as e:
        logging.error(f"邮件发送失败: {e}")
    finally:
        server.quit()

if __name__ == "__main__":
    # 邮件内容
    subject = "邮件主题"
    text = "这里是普通文本内容"
    html = """
    <html>
      <body>
        <p>这里是HTML内容</p>
      </body>
    </html>
    """

    # 创建邮件
    # 邮件中如果需要添加html格式内容,可添加,如不需要,则忽略
    message = create_email(subject, sender_email, receiver_emails, text, html)

    # 发送邮件
    send_email(sender_email, password, receiver_emails, message)

二 进阶用法:定时发送邮件

定时发送邮件是一个常见需求,比如每日发送报告或每周发送提醒。我们可以使用Python的schedule库来实现这一功能。

安装schedule
pip install schedule
修改代码以支持定时发送
import os
import smtplib
import logging
import schedule
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 邮件发送者和接收者
sender_email = os.getenv("SENDER_EMAIL")
password = os.getenv("EMAIL_PASSWORD")
receiver_emails = ["receiver1@example.com", "receiver2@example.com", "receiver3@example.com"]

# 设置日志记录
logging.basicConfig(level=logging.INFO, filename='./logs/email_log.txt', filemode='a',
                    format='%(asctime)s - %(levelname)s - %(message)s')

def create_email(subject, sender_email, receiver_emails, text, html):
    """创建邮件对象和设置邮件内容"""
    message = MIMEMultipart("alternative")
    message["Subject"] = subject
    message["From"] = sender_email
    message["To"] = ', '.join(receiver_emails)
    
    part1 = MIMEText(text, "plain")
    part2 = MIMEText(html, "html")
    
    message.attach(part1)
    message.attach(part2)
    
    return message

def send_email(sender_email, password, receiver_emails, message):
    """发送邮件"""
    try:
        server = smtplib.SMTP_SSL("smtp.qq.com", 465)
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_emails, message.as_string())
        logging.info("邮件发送成功")
    except smtplib.SMTPAuthenticationError:
        logging.error("邮件发送失败: 认证错误")
    except smtplib.SMTPRecipientsRefused:
        logging.error("邮件发送失败: 收件人被拒绝")
    except smtplib.SMTPSenderRefused:
        logging.error("邮件发送失败: 发件人被拒绝")
    except smtplib.SMTPException as e:
        logging.error(f"邮件发送失败: {e}")
    finally:
        server.quit()

def job():
    """定时任务"""
    # 邮件内容
    subject = "定时邮件主题"
    text = "这里是定时邮件的普通文本内容"
    html = """
    <html>
      <body>
        <p>这里是定时邮件的HTML内容</p>
      </body>
    </html>
    """

    # 创建邮件
    message = create_email(subject, sender_email, receiver_emails, text, html)

    # 发送邮件
    send_email(sender_email, password, receiver_emails, message)

if __name__ == "__main__":
    # 设置定时任务
    schedule.every().day.at("09:00").do(job)  # 每天早上9点执行任务

    while True:
        schedule.run_pending()
        time.sleep(1)
说明:
  1. 安装schedule:使用pip install schedule安装定时任务库。
  2. 定义定时任务job:将发送邮件的逻辑封装在job函数中。
  3. 设置定时任务:使用schedule.every().day.at("09:00").do(job)设置每天早上9点执行任务。
  4. 持续运行定时任务:使用while True循环持续运行定时任务。

总结

通过以上步骤,我们实现了使用Python发送邮件的基本功能,并通过定时任务扩展了其功能。定时发送邮件在许多应用场景中非常实用,比如定期报告、提醒和通知等。希望这篇博客对你有所帮助,能够在实际项目中应用这些技巧,提高工作效率。

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sssugarr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值