python发送邮件(flask / smtplib)
基于smtplib
def start():
# 邮箱服务地址
mail_host = 'smtp.qq.com'
# 邮箱用户名
mail_user = ''
# 邮箱密码
mail_pass = ''
# 邮件发送方邮箱地址
sender = ''
# 邮件接受方邮箱地址,注意这里是一个列表<list>,这意味着你可以写多个邮件地址群发
receivers = ['']
# 设置email信息
# 设置邮件内容
message = MIMEText('使用rpa为您发送邮件', 'plain', 'utf-8')
# 邮件主题
message['Subject'] = '邮件测试'
# 发送方信息
message['From'] = sender
# 接受方信息
message['To'] = receivers[0]
# 登录并发送邮件
try:
smtpObj = smtplib.SMTP_SSL()
# 连接到服务器
smtpObj.connect(mail_host, 465)
# 登录
smtpObj.login(mail_user, mail_pass)
# 发送信息
smtpObj.sendmail(sender, receivers, message.as_string())
# 退出
smtpObj.quit()
print('邮件发送成功~')
except smtplib.SMTPException as e:
print('error: ' + e)
基于flask
# 使用上下文管理器封装接口
def send_async_email(app, msg):
with app.app_context():
try:
mail.send(msg)
except Exception as e:
pass
# 定义邮件体
def send_email(to, subject, template, **kwargs):
app = current_app._get_current_object()
msg = Message('标题' + ' ' + '内容',
sender=app.config['MAIL_SENDER'], recipients=[to])
# msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
# 多线程发布
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
本文来自博客园,作者:七夜魔手,转载请注明原文链接:https://www.cnblogs.com/ranbox/p/18461095