欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用smtplib和email封装python发送邮件模块类分享

程序员文章站 2023-08-14 09:07:46
复制代码 代码如下:#!/usr/bin/python# encoding=utf-8# filename: send_email.pyfrom email.mime.im...

复制代码 代码如下:

#!/usr/bin/python
# encoding=utf-8
# filename: send_email.py
from email.mime.image import mimeimage
from email.mime.multipart import mimemultipart
from email.mime.text import mimetext 
import smtplib 


class sendemail:
    # 构造函数:初始化基本信息
    def __init__(self, host, user, passwd):
        linfo = user.split("@")
        self._user = user
        self._account = linfo[0]
        self._me = self._account + "<" + self._user + ">"

        server = smtplib.smtp() 
        server.connect(host) 
        server.login(self._account, passwd)
        self._server = server     

    # 发送文件或html邮件   
    def sendtxtmail(self, to_list, sub, content, subtype='html'):   
        # 如果发送的是文本邮件,则_subtype设置为plain
        # 如果发送的是html邮件,则_subtype设置为html
        msg = mimetext(content, _subtype=subtype, _charset='utf-8') 
        msg['subject'] = sub 
        msg['from'] = self._me 
        msg['to'] = ";".join(to_list) 
        try:
            self._server.sendmail(self._me, to_list, msg.as_string())  
            return true 
        except exception, e: 
            print str(e) 
            return false

    # 发送带附件的文件或html邮件      
    def sendattachmail(self, to_list, sub, content, subtype='html'):
        # 创建一个带附件的实例
        msg = mimemultipart() 
        # 增加附件1
        att1 = mimetext(open(r'd:\javawork\pytest\src\main.py','rb').read(), 'base64', 'utf-8')
        att1["content-type"] = 'application/octet-stream'
        # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
        att1["content-disposition"] = 'attachment; filename="main.py"'
        msg.attach(att1)

        # 增加附件2
        att2 = mimetext(open(r'd:\javawork\pytest\src\main.py','rb').read(), 'base64', 'utf-8')
        att2["content-type"] = 'application/octet-stream'
        att2["content-disposition"] = 'attachment; filename="main.txt"'
        msg.attach(att2)

        # 增加邮件内容
        msg.attach(mimetext(content, _subtype=subtype, _charset='utf-8'))

        msg['subject'] = sub 
        msg['from'] = self._me
        msg['to'] = ";".join(to_list)

        try:
            self._server.sendmail(self._me, to_list, msg.as_string())  
            return true 
        except exception, e: 
            print str(e) 
            return false
     # 发送带附件的文件或html邮件      
    def sendimagemail(self, to_list, sub, content, subtype='html'):
        # 创建一个带附件的实例
        msg = mimemultipart()

        # 增加邮件内容
        msg.attach(mimetext(content, _subtype=subtype, _charset='utf-8'))

        # 增加图片附件
        image = mimeimage(open(r'd:\javawork\pytest\src\test.jpg','rb').read())
        #附件列表中显示的文件名
        image.add_header('content-disposition', 'attachment;filename=p.jpg')    
        msg.attach(image) 

        msg['subject'] = sub 
        msg['from'] = self._me
        msg['to'] = ";".join(to_list)

        try:
            self._server.sendmail(self._me, to_list, msg.as_string())  
            return true 
        except exception, e: 
            print str(e) 
            return false

    # 析构函数:释放资源 
    def __del__(self):
        self._server.quit()
        self._server.close()

mailto_list = ['xxx@163.com']
mail = sendemail('smtp.163.com', 'xxx@163.com', 'xxxxxx')
if mail.sendtxtmail(mailto_list, "测试邮件", "hello world!<br><br><h1>你好,发送文本文件测试<h1>"): 
    print "发送成功" 
else: 
    print "发送失败"

if mail.sendattachmail(mailto_list, "测试邮件-带两个附件", "hello world!<br><br><h1>你好,发送文本文件测试<h1>"): 
    print "发送成功" 
else: 
    print "发送失败"

if mail.sendimagemail(mailto_list, "测试邮件-带一个图片的附件", "hello world!<br><br><h1>你好,发送文本文件测试<h1>"): 
    print "发送成功" 
else: 
    print "发送失败"