Python开发【模块】:邮件

邮件

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-8 -*-

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)[0]
        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文件

 

  

  

 

 

 

  

 

转载于:https://www.cnblogs.com/lianzhilei/p/6530298.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值