Python 自动发送邮箱(给npy送上美美的祝福~)
准备工作:开通电子邮箱的SMTP功能(以QQ邮箱为例)
打开QQ邮箱首页=>进入“设置”
进入“账户”模块:
手机发送短信,开启STMP功能:
将获取的授权码保存下来,下面代码实现中需要使用到。
代码实现:
import smtplib
from email.mime.text import MIMEText
import datetime
SENDER = "280XXXXXX464@qq.com" #发送者邮箱
RECEIVER = ["250XXXXXX13@qq.com"] #接收者邮箱
SENDERNAME = "yzy" #发送者名称
RECEIVERNAME = 'lxh' #接收者名称
AUTHORIZATION = "XXXXXX" #发送者的授权码(从qq邮箱获取)
TITLE = '七夕节快乐' #邮件标题
TEXTBODY = '宝贝七夕快乐(*^_^*)' #邮件正文
SCHEDULED_TIME = datetime.datetime(2021, 8, 14, 5, 20, 00) #邮件发送时间:2021/8/14 5:20
def sendMail(subject, body):
msg = MIMEText(body) #正文
msg['Subject'] = subject # 标题
msg['From'] = SENDERNAME
msg['To'] = RECEIVERNAME
mail = smtplib.SMTP()
mail.connect("smtp.qq.com") # 连接 qq 邮箱
mail.login(SENDER, AUTHORIZATION) # 账号和授权码
mail.sendmail(SENDER,RECEIVER , msg.as_string())
print('{}将在{}启动向{}发送一封邮件'.format(SENDER,SCHEDULED_TIME,RECEIVER))
while True:
now = datetime.datetime.now().replace(microsecond=0)
if now == SCHEDULED_TIME:
sendMail(TITLE,TEXTBODY)
break # 不写break的话,也可以增加scheduled_time的值。如果都不写,会遇到重复运行的问题