python smtplib库发送邮件板子
发送代码
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import json
# 读取配置文件
with open("conf.json", encoding="utf-8") as fp:
json_data = json.load(fp)
sender = json_data.get('sender') # 获得发送者
password = json_data.get('password') # 获得口令
try:
smtp_obj = smtplib.SMTP('smtp.163.com', 25)
if 250 == smtp_obj.ehlo()[0]:
# 向smtp服务器打招呼,如果返回250,则问候成功
print("连接成功")
if 220 == smtp_obj.starttls()[0]:
# 返回220表示加密成功
print("tls加密成功")
if 235 == smtp_obj.login(sender, password)[0]:
# 登录邮箱,返回235表示登录成功
print("登录成功")
receivers = json_data.get('receivers') # 获取接受者列表
message = MIMEText(_text='你好呀我是李四', _subtype='plain', _charset='utf-8') # 构建发送信息主体
message['subject'] = Header("我就想测试一下", 'utf-8')
message['from'] = "<%s>" % sender
for receiver in receivers:
# 发送信息
message['to'] = u"大可爱<%s>" % receiver
smtp_obj.sendmail(sender, receivers,message.as_string()) # 发送邮件
if 221 == smtp_obj.quit()[0]:
# 与服务器断开,如果返回221表示会话结束
print("发送结束,断开服务成功")
except Exception:
print("发送失败")
配置文件
{
“sender”: “你的发送邮箱地址”,
“password”: “开通smtp服务给的一次性口令”,
“receivers”: [“接收人的列表”]
}