欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python使用smtplib模块发送邮件

程序员文章站 2022-07-10 15:24:20
...
import smtplib
from email.mime.text import MIMEText
msg_from = '[email protected]'  # 发送方邮箱
passwd = 'resmobdda'  # 填入发送方邮箱的授权码
msg_to = "[email protected]" # 收件人邮箱 ,可以一次发给多个人
mail_host="smtp.qq.com" #服务器
port= 465 #端口号
subject = "儿童中心"  # 主题
content = f"""
    <span>亲爱的</span>{msg_to}
    <div>您的邮箱验证码是:123456</div>
    <div>请输入验证码,完成验证</div> 
"""
msg = MIMEText(content,"html",'utf-8')#三个参数:第一个为文本内容,第二个MIME的subtype,设置文本格式,传入'plain',最终的MIME就是'text/plain',第三个 utf-8 设置编码
#plain 页面上原样显示这段代码
msg['Subject'] = subject
msg['From'] =  msg_from
msg['To'] = msg_to
#创建连接对象并连接到
s = smtplib.SMTP_SSL(mail_host,port)  # 邮件服务器及端口号
# 登录服务器
s.login(msg_from, passwd)
try:
    s.sendmail(msg_from,msg_to, msg.as_string())
    print("发送成功")
except Exception as e:
    print(e)
    print("发送失败")
finally:
    s.quit()