说明:python虽然有smtplib包,但发送邮件时自己要写的代码还是有点多,无法做到拿到即用,所以封装一下。

MailTool:邮件工具类,实例化后可直接调用其方法
send():发送邮件,可处理附件,发送给多人等

#!/usr/bin/env python
# coding=utf-8
"""
Author: DENGQINGYONG
Time:   17/2/10 11:05 
Desc:   发送邮件示例代码
""" 

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from os.path import exists


class MailTool(object):
    """
        用途:
            邮件发送工具
        参数:
            send_username:  发送者邮箱
            send_smtp:      发送者邮箱对应的smtp服务器地址
            send_password:  发送都邮箱密码
    """
    def __init__(self, send_username, send_smtp=None, send_password=None,):
        """初始化实例,需要提供发送方信息:发送smtp服务器,用户名,密码等"""
        self.send_smtp = send_smtp
        self.send_username = send_username
        self.send_password = send_password

    def send(self, receiver, subject, content, mail_format="plain", mail_charset="utf-8", attachs=None):
        """
            发送邮件
            参数: 
                receiver:接收人邮箱列表, 
                subject:邮件主题, 
                content:邮件主题, 
                mail_format:邮件格式,取值有plain和html, 
                mail_charset:邮件字符集, 
                attachs:附件路径列表    
        """
        # 转换正文类型为规范类型
        if mail_format == "text":
            mail_format = "plain"

        # 处理邮件正文格式
        if mail_format == "plain":
            print content
            pass
        elif mail_format == "html":
            content = "<html><body>%s</body></html>" % content
            print content
        else:
            print "邮件格式输入错误: %s, 应该为text或html" % mail_format
            return 1
        msg = MIMEText(content, mail_format, mail_charset)
        msg["Subject"] = Header(subject, mail_charset)
        msg["From"] = Header(self.send_username, mail_charset)
        if isinstance(receiver, (list, tuple)):
            msg["To"] = Header(', '.join(receiver), 'utf-8')
        else:
            msg["To"] = Header(receiver, mail_charset)

        # 处理附件
        if attachs:
            msg = self.attachment(msg, attachs)

        smtp = smtplib.SMTP()
        smtp.connect(self.send_smtp)
        smtp.login(self.send_username, self.send_password)
        smtp.sendmail(self.send_username, receiver, msg.as_string())
        smtp.quit()

    def attachment(self, msg, attachs):
        """处理附件,将附件添加到邮件中"""
        msg_part = MIMEMultipart()
        msg_part["From"] = msg["From"]
        msg_part["To"] = msg["To"]
        msg_part["Subject"] = msg["Subject"]
        # print msg.get_payload(decode=True)
        msg_part.attach(msg)
        if isinstance(attachs, (list, tuple)):
            for attach in attachs:
                msg_part = self.add_attach(msg_part, attach)
        else:
            msg_part = self.add_attach(msg_part, attachs)
        return msg_part

    def add_attach(self, attobj, filename):
        """将单个文件添加到附件对象中"""
        if exists(filename):
            attachname = filename.split('/')[-1]
            if len(filename) == 0:
                attachname = filename.split('\\')[-1]
        else:
            raise IOError("文件不存: %s" % filename)
        attach = MIMEText(open(filename, "rb").read(), "base64", "utf-8")
        attach["Content-Type"] = "application/octet-stream"
        attach["Content-Disposition"] = "attachment; filename='%s'" % attachname
        attobj.attach(attach)
        return attobj

if __name__=="__main__":
    attachs = [u'/Users/dengqingyong/Work/SN.txt', u'/Users/dengqingyong/Downloads/商户入驻申请更改.png']
    receiver = ['it_xxx@qq.com', 'it_xxx@aliyun.com']
    mail = MailTool("yu12377@163.com", "smtp.163.com", "password")
    mail.send(receiver, u'优美诗词收藏', u'多情自古空余恨,好梦右来最易醒。——清·史清《溪佚题》', 'plain', attachs=attachs)
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐