Python smtplib实现发送邮件功能
本文实例为大家分享了Pythonsmtplib发送邮件功能的具体代码,供大家参考,具体内容如下
解决之前版本的问题,下面为最新版
#!/usr/bin/envpython #coding:gbk """ FuncName:sendemail.py Desc:sendemailwithtext,image,audio,application... Date:2016-06-2010:30 Home:http://blog.csdn.net/z_johnny Author:johnny """ fromemail.mime.multipartimportMIMEMultipart fromemail.mime.applicationimportMIMEApplication fromemail.utilsimportCOMMASPACE fromemail.mime.textimportMIMEText fromemail.mime.imageimportMIMEImage fromemail.mime.audioimportMIMEAudio importConfigParser importsmtplib importos classMyEmail: def__init__(self,email_config_path,email_attachment_path): """ initconfig """ config=ConfigParser.ConfigParser() config.read(email_config_path) self.attachment_path=email_attachment_path self.smtp=smtplib.SMTP() self.login_username=config.get('SMTP','login_username') self.login_password=config.get('SMTP','login_password') self.sender=config.get('SMTP','login_username')#sameaslogin_username self.receiver=config.get('SMTP','receiver') self.host=config.get('SMTP','host') #self.port=config.get('SMTP','port')发现加入端口后有时候发邮件出现延迟,故暂时取消 defconnect(self): """ connectserver """ #self.smtp.connect(self.host,self.port) self.smtp.connect(self.host) deflogin(self): """ loginemail """ try: self.smtp.login(self.login_username,self.login_password) except: raiseAttributeError('Cannotloginsmtp!!!') defsend(self,email_title,email_content): """ sendemail """ msg=MIMEMultipart()#createMIMEMultipart msg['From']=self.sender#sender receiver=self.receiver.split(",")#splitreceivertosendmoreuser msg['To']=COMMASPACE.join(receiver) msg['Subject']=email_title#emailSubject content=MIMEText(email_content,_charset='gbk')#addemailcontent,codingisgbk,becasuechineseexist msg.attach(content) forattachment_nameinos.listdir(self.attachment_path): attachment_file=os.path.join(self.attachment_path,attachment_name) withopen(attachment_file,'rb')asattachment: if'application'=='text': attachment=MIMEText(attachment.read(),_subtype='octet-stream',_charset='GB2312') elif'application'=='image': attachment=MIMEImage(attachment.read(),_subtype='octet-stream') elif'application'=='audio': attachment=MIMEAudio(attachment.read(),_subtype='octet-stream') else: attachment=MIMEApplication(attachment.read(),_subtype='octet-stream') attachment.add_header('Content-Disposition','attachment',filename=('gbk','',attachment_name)) #makesure"attachment_nameischinese"right msg.attach(attachment) self.smtp.sendmail(self.sender,receiver,msg.as_string())#formatmsg.as_string() defquit(self): self.smtp.quit() defsend(): importtime ISOTIMEFORMAT='_%Y-%m-%d_%A' current_time=str(time.strftime(ISOTIMEFORMAT)) email_config_path='./config/emailConfig.ini'#configpath email_attachment_path='./result'#attachmentpath email_tiltle='johnnytest'+'%s'%current_time#asjohnnytest_2016-06-20_Monday,itcanchooseonlyfilewhenaddtime email_content='python发送邮件测试,包含附件' myemail=MyEmail(email_config_path,email_attachment_path) myemail.connect() myemail.login() myemail.send(email_tiltle,email_content) myemail.quit() if__name__=="__main__": #fromsendemailimportSendEmail send()
配置文件emailConfig.ini
路径要与程序对应
;login_username:登陆发件人用户名 ;login_password:登陆发件人密码 ;host:port:发件人邮箱对应的host和端口,如:smtp.163.com:25和smtp.qq.com:465 ;receiver:收件人,支持多方发送,格式(注意英文逗号):123456789@163.com,zxcvbnm@qq.com [SMTP] login_username=johnny@163.com login_password=johnny host=smtp.163.com port=25 receiver=johnny1@qq.com,johnny2@163.com,johnny3@gmail.com
之前版本出现的问题:
#!/usr/bin/envpython #coding:utf-8 ''''' FuncName:smtplib_email.py Desc:使用smtplib发送邮件 Date:2016-04-1114:00 Author:johnny ''' importsmtplib fromemail.mime.multipartimportMIMEMultipart fromemail.mime.textimportMIMEText fromemail.mime.baseimportMIMEBase fromemail.utilsimportCOMMASPACE,formatdate fromemailimportencoders defsend_email_text(sender,receiver,host,subject,text,filename): asserttype(receiver)==list msg=MIMEMultipart() msg['From']=sender msg['To']=COMMASPACE.join(receiver) msg['Subject']=subject msg['Date']=formatdate(localtime=True) msg.attach(MIMEText(text))#邮件正文内容 forfileinfilename:#邮件附件 att=MIMEBase('application','octet-stream') att.set_payload(open(file,'rb').read()) encoders.encode_base64(att) iffile.endswith('.html'):#若不加限定,jpg、html等格式附件是bin格式的 att.add_header('Content-Disposition','attachment;filename="今日测试结果.html"')#强制命名,名称未成功格式化,如果可以解决请联系我 eliffile.endswith('.jpg')orfile.endswith('.png'): att.add_header('Content-Disposition','attachment;filename="pic.jpg"') else: att.add_header('Content-Disposition','attachment;filename="%s"'%file) msg.attach(att) smtp=smtplib.SMTP(host) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(username,password) smtp.sendmail(sender,receiver,msg.as_string()) smtp.close() if__name__=="__main__": sender='qqq@163.com' receiver=['www@qq.com'] subject="测试" text="johnny'labtest" filename=[u'测试报告.html','123.txt',u'获取的信息.jpg'] host='smtp.163.com' username='qqq@163.com' password='qqq' send_email_text(sender,receiver,host,subject,text,filename)
已测试通过,使用Header并没有变成“头”,故未使用
若能解决附件格式为(html、jpg、png)在邮箱附件中格式不为“bin”的请联系我,希望此对大家有所帮助,谢谢(已解决,见上面最新版)
点击查看:Python邮件smtplib发送示例
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。