使用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)
说明:
- 安装
schedule
库:使用pip install schedule
安装定时任务库。 - 定义定时任务
job
:将发送邮件的逻辑封装在job
函数中。 - 设置定时任务:使用
schedule.every().day.at("09:00").do(job)
设置每天早上9点执行任务。 - 持续运行定时任务:使用
while True
循环持续运行定时任务。
总结
通过以上步骤,我们实现了使用Python发送邮件的基本功能,并通过定时任务扩展了其功能。定时发送邮件在许多应用场景中非常实用,比如定期报告、提醒和通知等。希望这篇博客对你有所帮助,能够在实际项目中应用这些技巧,提高工作效率。