博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python mail
阅读量:5173 次
发布时间:2019-06-13

本文共 4524 字,大约阅读时间需要 15 分钟。

转载一个不错python mail封装

#!/usr/bin/pythonfrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEBase import MIMEBasefrom email import Utils, Encodersimport mimetypes, sys,smtplib,socket,getoptclass SendMail:    def __init__(self,smtp_server,from_addr,to_addr,user,passwd):        self.mailserver=smtp_server        self.from_addr=from_addr        self.to_addr=to_addr        self.username=user        self.password=passwd    def attachment(self,filename):        fd=open(filename,'rb')        filename=filename.split('/')        mimetype,mimeencoding=mimetypes.guess_type(filename[-1])                if (mimeencoding is None) or (mimetype is None):            mimetype='application/octet-stream'               maintype,subtype=mimetype.split('/')        if maintype=='text':            retval=MIMEText(fd.read(), _subtype=subtype, _charset='utf-8')                  else:            retval=MIMEBase(maintype,subtype)            retval.set_payload(fd.read())            Encoders.encode_base64(retval)            retval.add_header('Content-Disposition','attachment',filename=filename[-1])            fd.close()        return retval    def msginfo(self,msg,subject,filename):         # message = """Hello, ALL        #This is test message.        #--Anonymous"""        message=msg        msg=MIMEMultipart()        msg['To'] = self.to_addr        msg['From'] = 'sa <'+self.from_addr+'>'        msg['Date'] = Utils.formatdate(localtime=1)        msg['Message-ID'] = Utils.make_msgid()        if subject:            msg['Subject'] = subject        if message:            body=MIMEText(message,_subtype='plain',_charset='utf-8')            msg.attach(body)        #for filename in sys.argv[1:]:        if filename:            msg.attach(self.attachment(filename))        return msg.as_string()    def send(self,msg=None,subject=None,filename=None):        try:            s=smtplib.SMTP(self.mailserver)            try:                s.login(self.username,self.password)            except smtplib.SMTPException,e:                print "Authentication failed:",e                sys.exit(1)            s.sendmail(self.from_addr,self.to_addr.split(','),self.msginfo(msg,subject,filename))        except (socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:            print "*** Your message may not have been sent!"            print e            sys.exit(2)        else:            print "Message successfully sent to %d recipient(s)" %len(self.to_addr)if __name__=='__main__':    def usage():        print """Useage:%s [-h] -s 
-f
-t
-u
-p
[-S
-m
-F
] Mandatory arguments to long options are mandatory for short options too. -f, --from= Sets the name of the "from" person (i.e., the envelope sender of the mail). -t, --to= Addressee's address. -t "test@test.com,test1@test.com". -u, --user= Login SMTP server username. -p, --pass= Login SMTP server password. -S, --subject= Mail subject. -m, --msg= Mail message.-m "msg, ......." -F, --file= Attachment file name. -h, --help Help documen. """ %sys.argv[0] sys.exit(3) try: options,args=getopt.getopt(sys.argv[1:],"hs:f:t:u:p:S:m:F:","--help --server= --from= --to= --user= --pass= --subject= --msg= --file=",) except getopt.GetoptError: usage() sys.exit(3) server=None from_addr=None to_addr=None username=None password=None subject=None filename=None msg=None for name,value in options: if name in ("-h","--help"): usage() if name in ("-s","--server"): server=value if name in ("-f","--from"): from_addr=value if name in ("-t","--to"): to_addr=value if name in ("-u","--user"): username=value if name in ("-p","--pass"): password=value if name in ("-S","--subject"): subject=value if name in ("-m","--msg"): msg=value if name in ("-F","--file"): filename=value if server and from_addr and to_addr and username and password: test=SendMail(server,from_addr,to_addr,username,password) test.send(msg,subject,filename) else: usage()

 

测试脚本

#!/usr/bin/env python#coding=utf-8'''Created on Jul 23, 2016@author: Ca0Gu0'''import sysfrom mail import SendMailserver="smtp.xxx.com"from_addr="ops@163.com"to_addr="xxxx@139.com"username="ops@163.com"password="xxxxx"subject="Hi,喵星人"filename=Nonemsg="我来自遥远的星球"if server and from_addr and to_addr and username and password:    test=SendMail(server,from_addr,to_addr,username,password)    test.send(msg,subject,filename)

 

转载于:https://www.cnblogs.com/caoguo/p/5709473.html

你可能感兴趣的文章
初识maven及其安装步骤!!
查看>>
Linux终端基本命令
查看>>
课后作业四
查看>>
希尔排序----java实现
查看>>
php常用header头信息收藏
查看>>
fenby C语言 P26
查看>>
阿里云开发者大会:资源加应用酝酿云存储变局
查看>>
[HNOI 2001]产品加工
查看>>
Top 10 Java Debugging Tips with Eclipse
查看>>
bzoj 4556: [Tjoi2016&Heoi2016]字符串
查看>>
HDU4287 字典树
查看>>
PHP中的时间
查看>>
团队绩效评估
查看>>
最活跃FPGA论坛推荐社区
查看>>
SecurityException: No read access to the texture data. Unity WWW
查看>>
java官网下载
查看>>
codeforce 702C Cellular Network 二分答案
查看>>
如何彻底禁用 werfalut.exe
查看>>
win 64 SSDT HOOK
查看>>
MongoDB(八)Mongodb——GridFS存储
查看>>