Python logging Smtplib e-mail

Source: Internet
Author: User

#!/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 = ServI nfo["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 M  Imemultipart 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 ("email address format is wrong, please fill it in correctly!") 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-in To_list:log_mai L.info ("Sent successfully! "+" "+str (To)) Else:log_mail.info (" sent successfully! "+" "+str (to_list)) return True except Exception,e: #log log_mail.error (" Send 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" F Ro = servinfo["userName"] + "@" + ".". Join (servinfo["HostName"].split (".")    [1:])  Server=login_mail (servinfo) to_list = "[email protected]" #to_list = ["[Email protected]",] 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]: Log GER = Mail_logger (log_conf,log_name) result = Send_mail (logger,server[1],fro,to_list,sub,content) else:p Rint server[1] Close_mail (server[1])

Under the same directory

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 e-mail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.