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使用time、datetime返回工作日列表实例代码

最近在学习python,动手做了一个自动填写日报的小工具;由于请求中包含时间,格式如:2016-08-04;所以就了解了一下python的时间日期相关函数;这里做简单记录。 函数功能非常...

Python时间差中seconds和total_seconds的区别详解

如下所示: import datetime t1 = datetime.datetime.strptime("2017-9-06 10:30:00", "%Y-%m-%d %H:...

python每次处理固定个数的字符的方法总结

首先,来看每次处理一个字符的情况,可以有如下方法去实现:方法一:复制代码 代码如下:    >>> a='1234567' &n...

对python中的for循环和range内置函数详解

对python中的for循环和range内置函数详解

如下所示: 1.for循环和range内置函数配合使用 range函数生成一个从零开始的列表, range(4)表示list:0123 range(1,11,2)表示从1开始到11-...

python实现复制文件到指定目录

这几天在做一个数据集,由于不是很熟悉Linux下的命令,所以特地用了强大的python来做。我之前有一个数据集但是我只要里面名称带有composite和normals的图片,所以找了网上...