首页 > 代码库 > Python logging smtplib 发邮件
Python logging smtplib 发邮件
#!/usr/bin/env python#-*- coding:utf-8 -*-#File:mail_send.pyclass Mail_Logger(): mailLogger = None def __init__(self,conf_file,name): import logging,logging.config logging.config.fileConfig(conf_file) #create logger self.mailLogger = logging.getLogger(name) self.mailLogger.setLevel(logging.NOTSET) def info(self,message): self.mailLogger.info(message) def error(self,message): self.mailLogger.error(message) #DEBUG, WARNING, CRITICAL"""if login return [True,server]else returm [False,exception]"""def login_mail(servInfo): import smtplib mail_host = servInfo["hostName"] mail_user = servInfo["userName"] mail_pass = servInfo["password"] try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user,mail_pass) #log return [True,server] except Exception,e: print(str(e)) #log exit return [False,str(e)]def send_mail(log_mail,server,fro,to_list,sub,content,subtype="plain",charset="utf-8"): from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart content = MIMEText(content,_subtype=subtype,_charset=charset) msg = MIMEMultipart() msg[‘Subject‘] = sub msg["From"] = fro if isinstance(to_list,type([])): msg["To"]=";".join(to_list) elif isinstance(to_list,type("")): msg[‘To‘] =to_list else: log_mail("邮件地址格式错误,请正确填写!") exit() msg.attach(content) #log_mail = Mail_Logger("logging.conf","mail_log") try: server.sendmail(fro,to_list,msg.as_string()) if isinstance(to_list,type([])): for to in to_list: log_mail.info("发送成功!"+" "+str(to)) else: log_mail.info("发送成功!"+" "+str(to_list)) return True except Exception,e: #log log_mail.error("发送错误!"+" " +str(to_list)+":"+str(e)) return Falsedef close_mail(server): server.close()if __name__ == ‘__main__‘: servInfo = {} servInfo["hostName"] = ‘smtp.126.com‘ servInfo["userName"] = "username" servInfo["password"] = "paassword" fro = servInfo["userName"] + "@" +".".join(servInfo["hostName"].split(".")[1:]) server=login_mail(servInfo) to_list = "344164864@qq.com" #to_list = ["344164864@qq.com",] sub = "test subject" content = "testContent" log_conf = "logging.conf" log_name = "mail_log" #subtype = "palin html" #charset = "utf-8" #send_mail(logger,server[1],fro,to_list,sub,content(,subtype(,charset))) if server[0]: logger = Mail_Logger(log_conf,log_name) result = send_mail(logger,server[1],fro,to_list,sub,content) else: print server[1] close_mail(server[1])
在同个目录下
logging.conf:
[loggers]keys=root,example[handlers]keys=consoleHandler,rotateFileHandler[formatters]keys=simpleFormatter[formatter_simpleFormatter]format=[%(asctime)s](%(levelname)s)%(name)s: %(message)s[logger_root]level=DEBUGhandlers=consoleHandler,rotateFileHandler[logger_example]level=DEBUGhandlers=consoleHandler,rotateFileHandlerqualname=examplepropagate=0[handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,)[handler_rotateFileHandler]class=handlers.RotatingFileHandlerlevel=DEBUGformatter=simpleFormatterargs=(‘mailSend.log‘,‘a‘,200000,9)
Python logging smtplib 发邮件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。