python (18)在linux中如何实现定时发送邮件到指定邮箱,监测任务

最近要用到,定时发送邮件功能:

如何定时,当然要用到linux中crontab了

如下的代码能够定时发送邮件

 #!/usr/bin/env python
# -*- coding=utf-8 -*-
import smtplib
from email.mime.text import MIMEText
import threading
import time, datetime mailto_list=["lovychen@126.com"] #里面是对方的邮箱
#-----------QQ邮箱发送设置----------------------
mail_server="smtp.qq.com"#以qq邮箱为例子,里面是QQ邮箱的服务,换成其他邮箱需要更改服务
mail_user=""#这是QQ邮箱的账号
mail_pass=""#如果是其他的可以直接填上密码,如果用qq之类的,或者邮箱未开服务,会提醒你打开下面的链接
#QQ邮箱需要去官方打开服务:http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
def send_mail(to_list, sub, content):
msg = MIMEText(content,'plain','utf-8')
msg["Accept-Language"]="zh-CN"
msg["Accept-Charset"]="ISO-8859-1,utf-8"
msg['Subject'] = sub
msg['From'] = mail_user
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(mail_server)
server.starttls()
server.login(mail_user, mail_pass)
server.sendmail(mail_user, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False def getDate():
return str(datetime.datetime.utcfromtimestamp(time.time())+datetime.timedelta(hours=8)) def send_warning_mail(title, info):
nowTime = getDate()
try:
t = threading.Thread(target=send_mail, args=(mailto_list, title, str(nowTime) + " | " + str(info)))
t.start()
except:pass
# send_mail(mailto_list, "mysql异常", info) if __name__ == '__main__':
send_warning_mail("this is title", "\nthis is content")
# print 111

这是能够加上附件的邮件发送:

 #!/usr/bin/env python
#coding=utf-8
import smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
import time
mail_body='hello, this is the mail content'
mail_from=''#发件人的邮箱
mail_to=['']#收件人邮箱
# 构造MIMEMultipart对象做为根容器
msg=MIMEMultipart() # 构造MIMEText对象做为邮件显示内容并附加到根容器
body=MIMEText(mail_body)
msg.attach(body) # 构造MIMEBase对象做为文件附件内容并附加到根容器
# 等同于如下3行
#contype = 'application/octet-stream'
#maintype, subtype = contype.split('/', 1)
#part = MIMEBase(maintype, subtype)
part = MIMEBase('application', 'octet-stream') # 读入文件内容并格式化,此处文件为当前目录下,也可指定目录 例如:open(r'/tmp/123.txt','rb')
part.set_payload(open('123.txt','rb').read())
Encoders.encode_base64(part)
## 设置附件头
part.add_header('Content-Disposition', 'attachment; filename="herb.zip"')
msg.attach(part) # 设置根容器属性
msg['Subject']='this is the title'
msg['From']=mail_from
msg['To']=';'.join(mail_to)
msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z')
#如上得到了格式化后的完整文本msg.as_string()
#用smtp发送邮件
smtp=smtplib.SMTP()
smtp.connect('')#服务,如果是163的邮箱,就填上smtp.163.com
smtp.login('发件的邮箱','发件的密码')
smtp.sendmail(mail_from,mail_to,msg.as_string())
smtp.quit()
print 'ok'
上一篇:Mysql Update更新错误 Error Code:1175


下一篇:[荐]使用Js操作注册表