Python 发送邮件提醒
基于Smtplib 进行邮件发送
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
# 第三方 SMTP 服务
mail_host = "smtp.qq.com" # 设置服务器
mail_user = "darling@qq.com" # 用户名
mail_pass = "ddaasasasas" # 口令 QQ邮箱申请时的授权码
sender = 'darling@qq.com'
receivers = ['darling1@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 自定义发件人和收件人信息
# (可以在收到邮件的时候看到发件人和收件人信息),没设置该部分在收邮件时告知是未知发件人
def _format_addr(s):
addr = parseaddr(s)
return formataddr(addr)
# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = _format_addr(u'darling1 <%s>' % sender) # Header("darling1@qq.com", 'utf-8') # 发送者
for receiver in receivers:
message['To'] = _format_addr(u'<%s>' % receiver) # Header("测试", 'utf-8') # 接收者
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
try:
# 邮件服务器
smtplib.SMTP_SSL('smtp.exmail.qq.com')
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 587) # 25 为 SMTP 端口号
# smtpObj.starttls()
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
基于Yagmail 第三方库进行邮件发送
import yagmail
from loguru import logger
# 邮件发送
yagmail_server = yagmail.SMTP(user="darling@qq.com", password="ddaasasasas", host="smtp.qq.com")
# password 为QQ邮箱的授权码,其他邮箱,可以自行更换
email_name = ["darling1@qq.com", "darling2@qq.com"]
cc = ['darling3@qq.com'] # 抄送人
email_title = ["测试邮件"]
email_content = ["你好"]
# email_attachment = ["output.xlsx"] # 增加附件
yagmail_server.send(to=email_name, subject=email_title, contents=email_content, cc=cc)
yagmail_server.close()
logger.info("邮件发送完毕!")
惜秦皇汉武,略输文采;唐宗宋祖,稍逊风骚。
一代天骄,成吉思汗,只识弯弓射大雕。
俱往矣,数风流人物,还看今朝