一个python实例代码

发布时间:2020-08-20编辑:脚本学堂
本文介绍了pyhon发送邮件的一例代码,python发送邮件,用python监控restful接口是否正常,发送email,放在crontab 里面周期性检查,有需要的朋友参考下。

例子,python发送邮件 实现代码。
 

复制代码 代码示例:

#!/usr/bin/python 
import smtplib,email,sys   
from email.Message import Message   
import json 
import urllib2 
import httplib   
 
#define email info   
smtpserver='smtp.126.com'   
smtpuser='xxxx@126.com'   
smtppass='xxxxx'   
smtpport='25'   
to='xx@xx.com' 
subj='ispider data bi interface Alert' 
 
class MyEmail:   
        def __init__(self): 
                #"connect to smtp server and return a smtplib.SMTP instance object"   
                self.server=smtplib.SMTP(smtpserver,smtpport)   
                self.server.ehlo()   
                self.server.login(smtpuser,smtppass)   
                  
       
        def sendmessage(self,to,subj,content):   
                msg = Message()   
                msg['Mime-Version']='1.0'   
                msg['From']    = smtpuser   
                msg['To']      = to   
                msg['Subject'] = subj   
                msg['Date']    = email.Utils.formatdate()#curr datetime, rfc2822   
                msg.set_payload(content)   
                try:       
                        failed =self.server.sendmail(smtpuser,to,str(msg))# may also raise exc   
                except Exception ,ex:   
                        print Exception,ex   
                        print 'Error - send failed'   
                else:   
                        print "send success!"   
        def send(self,content): 
                self.sendmessage(to,subj,content) 
 
if __name__=="__main__":   

try: 
urllib2.urlopen('http://xx:8081/itemlist') 
         
except Exception,ex: 
        print Exception,ex 
        msg=str(Exception)+'n'+str(ex) 
        print msg 
        mymail=MyEmail() 
        mymail.send(msg) 
else: 
        print 'it works well'