邮件

1、简单发送

settings.py配置:

import os
import sys,string
from bin.start import BASE_DIR # 日志存放地址
RUN_LOG_FILE = os.path.join(BASE_DIR,'log','run.log')
ERROR_LOG_FILE = os.path.join(BASE_DIR,'log','error.log') # 邮件配置
SENDER = 'lianzhilei@yeah.net' # 发送邮件账号
RECEIVER = ['185130485@qq.com','593089304@qq.com','liuyufei@jcrb.com','lianzhilei0711@163.com',] # 接收邮件账号 多个接收账号用列表括起来[] # RECEIVER = 'lianzhilei0711@163.com' # 接收邮件账号
SMTPSERVER = 'smtp.yeah.net' # 发送邮件smtp地址
PASSWORD = 'lzl182105328' # 此为授权码需登录到邮件上设置 # 检索目录配置
DIRNAME = '/data/TRS/TRSWAS5.0/Tomcat/webapps/'
TIME = 1 #最近一天

mail.py邮件主体:

import smtplib
import traceback
from email.mime.text import MIMEText
from email.header import Header from config import settings
from lib.log import Logger def send_mail(subject,message):
'''
发送邮件
:param subject: 邮件标题
:param message: 邮件内容
:return:
'''
sender = settings.SENDER
receiver = settings.RECEIVER
smtpserver = settings.SMTPSERVER
password = settings.PASSWORD
print(receiver)
msg = MIMEText(message, 'plain', 'utf-8') # 第二个参数用plain!!不要用text!!不然报554错误
msg['Subject'] = Header(subject, 'utf-8') # 必须设置
msg['From'] = '正义检索报告<%s>'%sender # 必须设
msg['To'] = ",".join(receiver) # 必须设置 try:
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(sender, password)
smtp.sendmail(sender, receiver, msg.as_string(),rcpt_options=receiver)
smtp.quit()
msg = '邮件发送成功'
Logger().log(msg, True)
except Exception as e:
msg = traceback.format_exc()
Logger().log(msg,False)
#!/usr/bin/env python
# -*- coding:utf- -*- import sys
import logging
import os
from config import settings class Logger(object):
__instance = None def __init__(self):
self.run_log_file = settings.RUN_LOG_FILE
self.error_log_file = settings.ERROR_LOG_FILE
self.run_logger = None
self.error_logger = None self.initialize_run_log()
self.initialize_error_log() def __new__(cls, *args, **kwargs): # 单例模式
if not cls.__instance:
cls.__instance = object.__new__(cls, *args, **kwargs)
return cls.__instance @staticmethod
def check_path_exist(log_abs_file):
log_path = os.path.split(log_abs_file)[]
if not os.path.exists(log_path):
os.mkdir(log_path) def initialize_run_log(self):
self.check_path_exist(self.run_log_file)
file_1_1 = logging.FileHandler(self.run_log_file, 'a', encoding='utf-8')
fmt = logging.Formatter(fmt="%(asctime)s - %(levelname)s : %(message)s")
file_1_1.setFormatter(fmt)
logger1 = logging.getLogger('run_log') # 'run_log' 随意写
logger1.setLevel(logging.INFO) # 效果与error里logging.Logger一样
logger1.addHandler(file_1_1)
self.run_logger = logger1 def initialize_error_log(self):
self.check_path_exist(self.error_log_file)
file_1_1 = logging.FileHandler(self.error_log_file, 'a', encoding='utf-8')
fmt = logging.Formatter(fmt="%(asctime)s - %(levelname)s : %(message)s")
file_1_1.setFormatter(fmt)
logger1 = logging.Logger('run_log', level=logging.ERROR)
logger1.addHandler(file_1_1)
self.error_logger = logger1 def log(self, message, mode=True):
"""
写入日志
:param message: 日志信息
:param mode: True表示运行信息,False表示错误信息
:return:
"""
if mode:
self.run_logger.info(message)
else:
self.error_logger.error(message)

log.py文件

  

  

  

Python开发【模块】:邮件的更多相关文章

  1. python开发模块基础:re正则

    一,re模块的用法 #findall #直接返回一个列表 #正常的正则表达式 #但是只会把分组里的显示出来#search #返回一个对象 .group()#match #返回一个对象 .group() ...

  2. python开发模块基础:异常处理&hashlib&logging&configparser

    一,异常处理 # 异常处理代码 try: f = open('file', 'w') except ValueError: print('请输入一个数字') except Exception as e ...

  3. python开发模块基础:os&sys

    一,os模块 os模块是与操作系统交互的一个接口 #!/usr/bin/env python #_*_coding:utf-8_*_ ''' os.walk() 显示目录下所有文件和子目录以元祖的形式 ...

  4. python开发模块基础:序列化模块json,pickle,shelve

    一,为什么要序列化 # 将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化'''比如,我们在python代码中计算的一个数据需要给另外一段程序使用,那我们怎么给?现在我们能想到的方法就是存在文 ...

  5. python开发模块基础:time&random

    一,time模块 和时间有关系的我们就要用到时间模块.在使用模块之前,应该首先导入这个模块 常用方法1.(线程)推迟指定的时间运行.单位为秒. time.sleep(1) #括号内为整数 2.获取当前 ...

  6. python开发模块基础:collections模块&paramiko模块

    一,collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdic ...

  7. python开发模块基础:正则表达式

    一,正则表达式 1.字符组:[0-9][a-z][A-Z] 在同一个位置可能出现的各种字符组成了一个字符组,在正则表达式中用[]表示字符分为很多类,比如数字.字母.标点等等.假如你现在要求一个位置&q ...

  8. Python开发——目录

    Python基础 Python开发——解释器安装 Python开发——基础 Python开发——变量 Python开发——[选择]语句 Python开发——[循环]语句 Python开发——数据类型[ ...

  9. Python开发【第六篇】:模块

    模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才 ...

  10. python辅助开发模块(非官方)如pil,mysqldb,openpyxl,xlrd,xlwd

    官方文档 只是支持win32, 不支持win64 所以很麻烦 民间高人,集中做了一堆辅助库,下载后,用python安装目录下的scripts中,pip和easy_install就可以安装了 pytho ...

随机推荐

  1. Linux配置防火墙,开启80port、3306port 可能会遇到的小问题

     vi /etc/sysconfig/iptables -A INPUT -m state –state NEW -m tcp -p tcp –dport 80 -j ACCEPT(同意80端口通 ...

  2. tomcat server.xml docbase workdir

    在tomcat安装好后,只要把你的web项目copy到%TOMCAT_HOME%webapp下面就可以是使用啦!!其实还有种方法就是设定虚拟目录,即把项目的目录映射到tomcat中.这样做即可以不用重 ...

  3. VS2013+opencv2.4.9配置

    VS2013+opencv2.4.9(10)配置[zz] - yifeier12 - 博客园 http://www.cnblogs.com/cuteshongshong/p/4057193.html ...

  4. Centos6.5 安装配置docker

    宿主机:win7 64位   vagrant封装环境运行在VirtualBox 虚拟机上CentOS6.5,这是做测试时的一个环境,顺便错用安装docker玩玩.   centos6.5可以直接安装d ...

  5. oracle 无效索引

    错误信息:ORA-01502: index 'VOX_ID' or partition of such index is in unusable state 原因:将表的表空间做了更改,导致索引失效. ...

  6. 判断字符串是否为json字符串

    public static class JsonSplitExtention { public static bool IsJson(this string json) { return JsonSp ...

  7. js中如何跳出循环

    1.for循环中我们使用continue:终止本次循环计入下一个循环,使用break终止整个循环. 2.而在jquery中 $.each使用return true 终止本次循环计入下一个循环,retu ...

  8. 2.1 C语言下的位运算

    位运算符: 注:运算量仅仅能为整型和字符型数据,不能是实数型的数据. 当进行&运算时:0&1=0.1&0=0:1&1=1:0&0=0: 当进行|运算时:0|1= ...

  9. swift - 之 UIColor使用自定义的RGB配色

    1.10进制颜色 UIColor(red: /, green: /, blue: /, alpha: 0.5) 2.16进制颜色 UIColor(red: , green: , blue: , alp ...

  10. NodeJS-002-Expres启动

    1.打开app.js文件 2.在module.exports = app;之前输入: app.listen(8100,function(){ console.log("Server Star ...