利用python实现简单的邮件发送客户端示例
脚本过于简单,供学习和参考。主要了解一下smtplib库的使用和超时机制的实现。使用signal.alarm实现超时机制。
#!/usr/bin/envpython #-*-coding:utf-8-*- importtime importsys importlogging importsmtplib importsocket importsignal importConfigParser fromdatetimeimportdatetime fromemailimportencoders fromemail.headerimportHeader fromemail.mime.textimportMIMEText fromemail.utilsimportparseaddr,formataddr CONF_PATH="/etc/zabbix/alarm_email.conf" logging.basicConfig(level=logging.INFO, format='%(asctime)s[%(levelname)s]:%(message)s', filename='/var/log/zabbix/send_alarm_email.log') classEmailObject: def__init__(self,to_addr,content): self.timeout=10 self.retry=3 self.cp=self._parse_config() self.cpl=self._parse_config().sections() self.conf=dict(self.cp.items(self.cpl[0])) #commonhowtouseone self.to_addr=to_addr self.content=content #getConfigParser,forsectionselection def_parse_config(self): cp=ConfigParser.ConfigParser() cp.read(CONF_PATH) returncp #setbaseconfig def_conf_parse(self): self.subject="zabbix告警" self.from_addr=self.conf["from_addr"] self.password=self.conf["password"] self.smtp_server=self.conf["smtp_server"] def_msg_parse(self): #msg=self.content.split("*") #state="alarm"ifmsg[0]=="PROBLEM"else"ok" #severity=msg[1] #head_time=map(int,msg[2].split(".")) #tail_time=map(int,msg[3].split(":")) ##ifnothost? #event_type="host."+msg[4] #reason=msg[5].replace("_","") #alarm_id=int(msg[6]) #message=msg returnself.content def_change_server(self): #iflen=1andthisfuniscalled,meansthatallservershavabeentried if(len(self.cpl)>1): self.cpl.pop(0) self.retry=3 self.conf=dict(self.cp.items(self.cpl[0])) logging.info("Changeserverto{}".format(self.cpl[0])) self.send_email() else: logging.warning("Noservercouldbeused,trytoconfigmoreserver(nowis{})orincreasethetimeout[{}]!".format(self.cp.sections(),self.timeout)) exit() defsend_email(self): #signalhandle defhandler(signum,frame): ifself.retry>0: raiseAssertionError else: self._change_server() self._conf_parse() from_addr=self.from_addr password=self.password smtp_server=self.smtp_server timeout=self.timeout to_addr=self.to_addr msg=MIMEText(self.content,'plain','utf-8') msg['Subject']=Header(self.subject,'utf-8') msg['From']='AlarmEmail'+'<'+from_addr+'>' msg['To']="******@******.com" try: signal.signal(signal.SIGALRM,handler) signal.alarm(timeout) server=smtplib.SMTP_SSL(smtp_server,465) server.login(from_addr,password) server.sendmail(from_addr,to_addr,msg.as_string()) logging.info("Sendemailsuccessfully!From:[{}],To:[{}],Content:[{}]".format(from_addr,to_addr,self.content)) server.quit() exit() exceptAssertionError: self.retry-=1 logging.info("Begintoresendemailforthe{}thtimes".format(3-self.retry)) self.send_email() exceptsmtplib.SMTPAuthenticationError,e: logging.error("Server[{}]authenticationfailed".format(smtp_server)) self._change_server() ''' example: fromemailtestimportemailtest eb=emailtest.EmailObject("******@******.com","testcontent") eb.send_email() tips: increasetimeout: eb.timeout=10 increaseretrytimes: eb.retry=5 '''
配置文件参考如下:
[default]
from_addr=******@******.com
password=******
smtp_server=smtp.******.com
[163]
from_addr=******@163.com
password=******
smtp_server=smtp.163.com
[qq]
from_addr=******@qq.com
password=******
smtp_server=smtp.qq.com
以上这篇利用python实现简单的邮件发送客户端示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。