论坛首页 编程语言技术论坛

python3发送邮件

浏览 1380 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-03-29  
#!/usr/bin/python3
#!-*- coding: utf-8-*-

import smtplib
import time
import sys
import os
import logging
import logging.handlers

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
 

#time_out
CONN_TIME_OUT=10
MAIL_LOG_LEVEL=0
ENCODING="UTF-8"

KB=1024
MB=1024*KB

LEVELS = {'debug': logging.DEBUG,
          'info': logging.INFO,
          'warning': logging.WARNING,
          'error': logging.ERROR,
          'critical': logging.CRITICAL}
          
LOG_FILENAME = 'mail_helper_log.out'
#logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
#logger=logging.getLogger('MyLogger')
#handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=5*MB, backupCount=15, encoding=ENCODING)
#logger.addHandler(handler)

class MailHelper:
    """
        create an mailUtil instance and pass some vars.
        Usage:
            mailUtil=mail.MailHelper("mexcn01.nhncorp.cn",  "CN90056", "CN90056", smtp_port=25)
            mailUtil.setFrom("noreply@nhn.com")
            mailUtil.setLogLevel("info")
            mailUtil.send("A3mao.zzg@nhn.com", "subject", "body message")
    """
    def __init__(self, smtp_host, smtp_user, smtp_password, smtp_port=25, 
                        time_out=CONN_TIME_OUT):
        self.smtp_host=smtp_host
        self.smtp_port=smtp_port
        self.smtp_user=smtp_user
        self.smtp_password=smtp_password
        self.time_out=time_out
        self.mail=MIMEMultipart('related')
        self.alter=MIMEMultipart('alternative')
        self.mail.attach(self.alter) 
        self.debug_level=MAIL_LOG_LEVEL
        self.logger=logging.getLogger('MyLogger')
        logFile=os.path.join(os.getenv("HOME"), LOG_FILENAME) 
        self.handler = logging.handlers.RotatingFileHandler(logFile, 
                                maxBytes=5*MB, backupCount=15, encoding=ENCODING)
        self.logger.addHandler(self.handler)

    
    def setLogLevel(self, level_name):
        """
          set debug level, when 1 on else off
        """
        level = LEVELS.get(level_name, logging.NOTSET) 
        self.logger.setLevel(level)
        #logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
        
        # only debug can display the log message
        if(int(level)== 10):
          self.debug_level=1
        else:
          self.debug_level=MAIL_LOG_LEVEL  
          
    def setFrom(self, mail_from):
        """
            set mail from 
        """
        self._from=mail_from
        self.mail["From"]=mail_from

    def send(self, toAddr, subject, msg_body, msg_body_type='html', encoding=ENCODING):
        """
            send email
        """
        currentTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        self.logger.info("send messgae \n[\n\t  Subject : {0:>5} \n\t  From : {1} \n\t  To : {2} \n\t  Time : {3}\n\t  Message : {4:>5} \n] ".format(subject, self.mail["From"], toAddr, currentTime, msg_body))
        
        if (type(toAddr) == list):
            self.mail['To'] = ','.join(toAddr)
        elif (type(toAddr) == str):
            self.mail['To'] = toAddr
        else:
            raise Exception('invalid mail to')  

        if(msg_body_type == 'html'):
          self.alter.attach(MIMEText(msg_body, 'html', encoding))
        else:
          self.alter.attach(MIMEText(msg_body, 'plain', encoding))  

        self.mail['Subject'] = subject
        self.mail['Date'] = currentTime
        server = False
        try:
          server = smtplib.SMTP(self.smtp_host, self.smtp_port, self.time_out)
          server.set_debuglevel(self.debug_level)
          server.login(self.smtp_user, self.smtp_password)
          server.sendmail(self.mail["From"], self.mail['To'], self.mail.as_string())
          return  True
        except Exception as e: 
          logging.error(sys.exc_info())
          return False
        finally:
         server and server.quit() 
         self.logger.info("********************* send mail finished and quit ********************* ")

 

调用

 

   上面为文件 mail_helper.py

 

 mailhelper=mail.MailHelper(smtp_host,  smtp_user, smtp_password, smtp_port=25)
                mailhelper.setFrom(smtp_from)
                mailhelper.setLogLevel("info") 
                currentTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
                mailhelper.send(smtp_to, "Warning!! monitor mail : " + currentTime, content)
 
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics