python3用smtplib模块发邮件
创建一个函数:
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from mail_config import mail_host, sender_name, sender_password, receivers
from datetime import datetime
# send_mail(title, text) 给定邮件标题,邮件正文,使用SMTP_SSL发送
def send_mail(title='',text=''):
# 用MIMEText组装邮件的信息
msg = MIMEText(text)
msg['From'] = sender_name
msg['To'] = ", ".join(receivers)
msg['Subject'] = title
# 创建email服务器的实例,除了SSL以外,还有TTLS方式
mail = smtplib.SMTP_SSL(mail_host)
try:
# 用邮箱的账户登录服务器
mail.login(sender_name, sender_password)
# 发送邮件(注:receivers是一个收件人列表,类型是list;如果写成字符串的话,只有第一个收件人能收到邮件)
mail.sendmail(sender_name, receivers, msg.as_string())
print(str(datetime.now()) + ' : ' + "send mail success!")
except Exception as e:
print(str(datetime.now()) + ' : ' + "Error, send mail failed. : %s" % e)
finally:
mail.quit()
将其它参数配置写入config.py中:
# -*- coding: utf-8 -*-
"""
固定参数配置文件
"""
# mail配置
mail_host = 'xxx.xxx.xxx.xxx'
mail_port = 25
mail_ssl_port = 465
sender_name = 'xxx@xxx.com'
sender_password = 'xxxxxxxx'
receivers = ['aaa@xxx.com', 'bbb@xxx.com', 'ccc@xxx.com', ]
# 邮件标题可按需要设置多个,调用时,直接import就可以
err_mail_title = '这是一个异常邮件的标题'
nor_mail_title = '这是一个正常邮件的标题'
验证一下:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from send_mail import send_mail
from mail_config import err_mail_title, nor_mail_title
# 验证邮件发送功能
nor_text = "这是一个正常邮件的正文"
err_text = "这是一个异常邮件的正文"
send_mail(nor_mail_title, nor_text)
send_mail(err_mail_title, err_text)
以上。