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

yipeiwu_com5年前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中逗号的三种作用实例分析

本文实例讲述了Python中逗号的三种作用。分享给大家供大家参考。具体分析如下: 最近研究python  遇到个逗号的问题 一直没弄明白 今天总算搞清楚了 1.逗号在参数传递中...

python 遍历列表提取下标和值的实例

如下所示: for index,value in enumerate(['apple', 'oppo', 'vivo']): print(index,value) 以上这篇py...

python集合类型用法分析

本文实例分析了python集合类型用法。分享给大家供大家参考。具体分析如下: python的集合类型和其他语言类似, 是一个无序不重复元素集,我在之前学过的其他的语言好像没有见过这个类型...

numpy下的flatten()函数用法详解

flatten是numpy.ndarray.flatten的一个函数,其官方文档是这样描述的: ndarray.flatten(order='C') Return a copy of...

Python中的上下文管理器和with语句的使用

Python2.5之后引入了上下文管理器(context manager),算是Python的黑魔法之一,它用于规定某个对象的使用范围。本文是针对于该功能的思考总结。 为什么需要上下文管...