Python发送Email方法实例
程序员文章站
2023-11-22 12:21:52
本文以实例形式展示了python发送email功能的实现方法,有不错的实用价值的技巧,且功能较为完善。具体实现方法如下:
主要功能代码如下:
#/usr/bin...
本文以实例形式展示了python发送email功能的实现方法,有不错的实用价值的技巧,且功能较为完善。具体实现方法如下:
主要功能代码如下:
#/usr/bin/env python # -*- encoding=utf-8 -*- import base64 import smtplib from email.mime.multipart import mimemultipart from email.mime.text import mimetext class ccsendmail: def __init__(self,host="your.mailhost.com",username='fromuser@xxx.com',password='passwd'): self.__smtp=smtplib.smtp(host) self.__subject=none self.__content=none self.__from=none self.__to=[] self.__style='html' self.__charset='gb2312' self.username = username self.password = password self.fromalias='fromuser' #发件人别名 self.from2='' def close(self): try: self.__smtp.quit() except exception ,e: pass def setfromalias(self,alias): self.fromalias=alias def setstyle(self,style): self.__style = style def setfrom2(self,from2): self.from2=from2 def setsubject(self,subject): self.__subject=subject def setcontent(self,content): self.__content=content def setfrom(self,address): self.__from=address def addto(self,address): self.__to.append(address) def setcharset(self,charset): self.__charset=charset def send(self): try: self.__smtp.set_debuglevel(1) #login if necessary if self.username and self.password: self.__smtp.login(self.username,self.password) msgroot = mimemultipart('related') msgroot['subject'] = self.__subject aliasb6=base64.encodestring(self.fromalias.encode(self.__charset)) if len(self.from2)==0: msgroot['from'] = "=?%s?b?%s?=%s"%(self.__charset,aliasb6.strip(),self.__from) else: msgroot['from'] = "%s"%(self.from2) msgroot['to'] = ";".join(self.__to) msgalternative = mimemultipart('alternative') msgroot.attach(msgalternative) msgtext = mimetext(self.__content, self.__style,self.__charset) msgalternative.attach(msgtext) self.__smtp.sendmail(self.__from,self.__to,msgroot.as_string()) return true except exception,e: print "error ",e return false def clearrecipient(self): self.__to = [] #给单个人发送邮件 def sendhtml(self,address,title,content): self.setstyle('html') self.setfrom("<%s>"%self.username) if not isinstance(content,str): content = content.encode('gb18030') self.addto(address) self.setsubject(title) self.setcontent(content) ret = self.send() self.close() return ret #群发邮件 def sendmorehtml(self,addresslist,title,content): self.setstyle('html') self.setfrom("<%s>"%self.username) if not isinstance(content,str): content = content.encode('gb18030') for address in addresslist: self.addto(address) self.setsubject(title) self.setcontent(content) ret = self.send() self.close() return ret #测试 def main(): send=ccsendmail() send.sendhtml('touser@xxx.com',u'邮件标题',u'邮件内容') #send.sendmorehtml([touser1@xx.com,touser2@xx.com],u'邮件标题',u'邮件内容') if __name__=='__main__': main()
希望本文所述实例对大家的python程序设计有一定的帮助。