最近要用到,定时发送邮件功能:
如何定时,当然要用到linux中crontab了
目前代码只能发邮件,能发送附件的还在学习中,稍后补上
1 #!/usr/bin/env python 2 3 import smtplib 4 from email.mime.text import MIMEText 5 import threading 6 import time, datetime 7 8 mailto_list=[""] #里面是对方的邮箱 9 #-----------QQ邮箱发送设置---------------------- 10 mail_server="smtp.qq.com"#以qq邮箱为例子,里面是QQ邮箱的服务,换成其他邮箱需要更改服务 11 mail_user=""#这是QQ邮箱的账号 12 mail_pass="这里面写上16位的编码"#直接填上密码,或者邮箱未开服务,会提醒你打开下面的链接 13 #QQ邮箱需要去官方打开服务:http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256 14 def send_mail(to_list, sub, content): 15 msg = MIMEText(content,‘plain‘,‘utf-8‘) 16 msg["Accept-Language"]="zh-CN" 17 msg["Accept-Charset"]="ISO-8859-1,utf-8" 18 msg[‘Subject‘] = sub 19 msg[‘From‘] = mail_user 20 msg[‘To‘] = ";".join(to_list) 21 try: 22 server = smtplib.SMTP() 23 server.connect(mail_server) 24 server.starttls() 25 server.login(mail_user, mail_pass) 26 server.sendmail(mail_user, to_list, msg.as_string()) 27 server.close() 28 return True 29 except Exception, e: 30 print str(e) 31 return False 32 33 def getDate(): 34 return str(datetime.datetime.utcfromtimestamp(time.time())+datetime.timedelta(hours=8)) 35 36 def send_warning_mail(title, info): 37 nowTime = getDate() 38 try: 39 t = threading.Thread(target=send_mail, args=(mailto_list, title, str(nowTime) + " | " + str(info))) 40 t.start() 41 except:pass 42 # send_mail(mailto_list, "mysql异常", info) 43 44 if __name__ == ‘__main__‘: 45 send_warning_mail("this is title", "this is content") 46 # print 111
时间: 2024-12-27 23:13:18