【python基础】邮件发送

1. 效果预览

在这里插入图片描述

2. 代码实现

注意:授权码不是邮箱登陆密码,需要在邮箱设置中申请获取。

import smtplib
import time
from email.mime.text import MIMEText
from email.header import Header

mail_host='smtp.126.com'  # 126邮箱,别的邮箱需要改动,请自行查找
mail_user='******@126.com'  # 自己的邮箱
mail_password='*************'  # 自己邮箱的授权码
receivers=['********@qq.com']  # 接收者的邮箱
message=MIMEText(str(time.strftime("%Y-%m-%d-%H_%M", time.localtime(time.time()))),'plain','utf-8')  # 邮件内容
message['From']=mail_user
message['To']=receivers[0]
subject="测试邮件"  # 邮件标题
message['Subject']=Header(subject,"utf-8")
try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host)
    smtpObj.login(mail_user, mail_password)
    smtpObj.sendmail(mail_user, receivers, message.as_string())
    print("恭喜你!邮件发送成功")
    smtpObj.quit()

except smtplib.SMTPException as e:
    print("Error 无法发送邮件")
    print(e)
posted @ 2022-03-16 21:14  ccql  阅读(1)  评论(0编辑  收藏  举报  来源