最近要用到,定时发送邮件功能:
如何定时,当然要用到linux中crontab了
如下的代码能够定时发送邮件
1 #!/usr/bin/env python 2 # -*- coding=utf-8 -*- 3 import smtplib 4 from email.mime.text import MIMEText 5 import threading 6 import time, datetime 7 8 mailto_list=["lovychen@126.com"] #里面是对方的邮箱 9 #-----------QQ邮箱发送设置---------------------- 10 mail_server="smtp.qq.com"#以qq邮箱为例子,里面是QQ邮箱的服务,换成其他邮箱需要更改服务 11 mail_user=""#这是QQ邮箱的账号 12 mail_pass=""#如果是其他的可以直接填上密码,如果用qq之类的,或者邮箱未开服务,会提醒你打开下面的链接 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
这是能够加上附件的邮件发送:
1 #!/usr/bin/env python 2 #coding=utf-8 3 import smtplib 4 from email.MIMEText import MIMEText 5 from email.MIMEMultipart import MIMEMultipart 6 from email.MIMEBase import MIMEBase 7 from email import Encoders 8 import time 9 mail_body='hello, this is the mail content' 10 mail_from=''#发件人的邮箱 11 mail_to=['']#收件人邮箱 12 # 构造MIMEMultipart对象做为根容器 13 msg=MIMEMultipart() 14 15 # 构造MIMEText对象做为邮件显示内容并附加到根容器 16 body=MIMEText(mail_body) 17 msg.attach(body) 18 19 # 构造MIMEBase对象做为文件附件内容并附加到根容器 20 # 等同于如下3行 21 #contype = 'application/octet-stream' 22 #maintype, subtype = contype.split('/', 1) 23 #part = MIMEBase(maintype, subtype) 24 part = MIMEBase('application', 'octet-stream') 25 26 # 读入文件内容并格式化,此处文件为当前目录下,也可指定目录 例如:open(r'/tmp/123.txt','rb') 27 part.set_payload(open('123.txt','rb').read()) 28 Encoders.encode_base64(part) 29 ## 设置附件头 30 part.add_header('Content-Disposition', 'attachment; filename="herb.zip"') 31 msg.attach(part) 32 33 # 设置根容器属性 34 msg['Subject']='this is the title' 35 msg['From']=mail_from 36 msg['To']=';'.join(mail_to) 37 msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z') 38 #如上得到了格式化后的完整文本msg.as_string() 39 #用smtp发送邮件 40 smtp=smtplib.SMTP() 41 smtp.connect('')#服务,如果是163的邮箱,就填上smtp.163.com 42 smtp.login('发件的邮箱','发件的密码') 43 smtp.sendmail(mail_from,mail_to,msg.as_string()) 44 smtp.quit() 45 print 'ok'