python模块学习系列之邮件(smtlib, email)

python admin 10℃ 0评论

本节还可以顺便复习下logging类

邮件发送在运维监控,电商支付消息,运营推广中应用比较广泛

主要代码如下

#-*- coding:utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import logging, os
import sys
reload(sys)
sys.setdefaultencoding('utf8')

logging.basicConfig(level=logging.INFO,
    filename='mail.log',
    format='%(asctime)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger("mail")

host = 'smtp.qq.com'
port = 465
user = '774928735@qq.com'
passwd = 'xxxxxxxxxxx' //大家需要修改这些配置
receivers = ['774928735@qq.com', 'wei.liu@tee.com']
try:
    smtpObj = smtplib.SMTP_SSL(host, port)
    smtpObj.connect(host)
    smtpObj.login(user, passwd)
    msg = Message(user, to_user=user, subject='test', content='test html')
    smtpObj.sendmail(user, receivers, msg.getMessage())
except smtplib.SMTPException, e:
    logger.info(u'%s' % e)

邮件体消息类

class Message(object):
    def format_str(self, strs):
        if not isinstance(strs, unicode):
            strs = unicode(strs)
        return strs

    def __init__(self, from_user, to_user, subject, content, with_attach=False):
        '''
        :param from_user: 谁发过来的邮件
        :param to_user: 发给谁
        :param subject: 邮件主题
        :param content: 邮件内容
        :param with_attach: 邮件是否包含附件
        '''
        if with_attach:
            self._message = MIMEMultipart()
            self._message.attach(MIMEText(content, 'plain', 'utf-8'))
        else:
            self._message = MIMEText(content, 'plain', 'utf-8')

        self._message['Subject'] = Header(subject, 'utf-8')
        self._message['From'] = Header(self.format_str(from_user), 'utf-8')
        self._message['To'] = Header(self.format_str(to_user), 'utf-8')
        self._with_attach = with_attach

    def attach(self, file_path):
        if self._with_attach == False:
            print "Please init the Message with attr 'with_attach = True'"
            exit(1)
        if os.path.isfile(file_path) == False:
            print "The file doesn`t exist!"
            exit(1)
        atta = MIMEText(open(file_path, 'rb').read(), 'base64', 'utf-8')
        atta['Content-Type'] = 'application/octet-stream'
        atta['Content-Disposition'] = 'attachment; filename="%s"' % Header(os.path.basename(file_path), 'utf-8')
        self._message.attach(atta)

    def getMessage(self):
        return self._message.as_string()

 

转载请注明:朋克网 » python模块学习系列之邮件(smtlib, email)

喜欢 (0)
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址