python使用logging模块发送邮件代码示例

yipeiwu_com6年前Python基础

logging模块不只是能记录log,还能发送邮件,使用起来非常简单方便

#coding=utf-8 
''''' 
Created on 2016-3-21 
 
@author: Administrator 
''' 
import logging, logging.handlers 
class EncodingFormatter(logging.Formatter): 
 def __init__(self, fmt, datefmt=None, encoding=None): 
  logging.Formatter.__init__(self, fmt, datefmt) 
  self.encoding = encoding 
 def format(self, record): 
  result = logging.Formatter.format(self, record) 
  if isinstance(result, unicode): 
   result = result.encode(self.encoding or 'utf-8') 
    
  return result 
 
#zhangdongsheng@itouzi.com 
errlog = logging.getLogger() 
sh = logging.handlers.SMTPHandler("smtp.163.com", 'xigongda200608@163.com', '381084992@qq.com', 
    "logging from my app", 
    credentials=('xigongda200608', 'password'), 
    secure=()) 
errlog.addHandler(sh) 
sh.setFormatter(EncodingFormatter('%(message)s', encoding='utf-8')) 
errlog.error(u'追加文件时出错') 

总结

以上就是本文关于python使用logging模块发送邮件代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

使用优化器来提升Python程序的执行效率的教程

如果不首先想想这句Knuth的名言,就开始进行优化工作是不明智的。可是,你很快写出来加入一些特性的代码,可能会很丑陋,你需要注意了。这篇文章就是为这时候准备的。 那么接下来就是一些很有用...

python numpy 矩阵堆叠实例

在实际操作中,遇到了矩阵堆叠的操作,本来想着自己写一个函数,后来想,应该有库函数,于是一阵找寻 import numpy as np a = np.array([1,2,3]) b...

Python中fnmatch模块的使用详情

fnamtch就是filenamematch, 在python中利用符合linuxshell风格的匹配模块来进行文件名的匹配筛选工作。 fnmatch()函数匹配能力介于简单的字符串方法...

Python多线程threading模块用法实例分析

Python多线程threading模块用法实例分析

本文实例讲述了Python多线程threading模块用法。分享给大家供大家参考,具体如下: 多线程 - threading python的thread模块是比较底层的模块,python...

django模板结构优化的方法

模版结构优化 引入模版 有时候一些代码是在许多模版中都用到的。如果我们每次都重复的去拷贝代码那肯定不符合项目的规范。一般我们可以把这些重复性的代码抽取出来,就类似于Python中的函...