python自动发邮件
定时发邮件简单代码如下
from email.mime.text import MIMEText
from email.header import Header
import time
from datetime import datetime
import smtplib
mail_host = "smtp.qq.com" #qq邮箱服务地址,当让可以使用其他的,如163.。。
mail_user = '29*******77@qq.com'
mail_pass = 'ogjc**********dig' #去邮箱设置中获取授权码
def time_email():
#发送者邮箱
sender = '29*******77@qq.com'
#接收者邮箱
recevivers = ['64*******47@qq.com']
massage = MIMEText("python测试发邮件S...",'plain','utf-8')
massage['From'] = Header('发送者','utf-8')
massage['To'] = Header('接收者','utf-8')
subject = 'Python SMTP 邮件测试'
massage['Subject'] = Header(subject,'utf-8')
try:
smtpObj = smtplib.SMTP('smtp.qq.com')
smtpObj.connect(mail_host,25) #25为SMPT端口
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender,recevivers,massage.as_string())
print('发送成功')
except smtplib.SMTPException:
print ("Error: 无法发送邮件")
#加一个循环,使其一直运行到发送时间,发送完毕退出循环
avtive = True
while avtive:
#获取系统时间
gain_time = (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
if gain_time == '2020-06-17 14:30:30':
time_email()
avtive = False