发送email邮件带附件,发送带附件的邮件

 

#/usr/bin/env python
#coding=utf-8
#
#from_addr = 'xx@163.com'
#password = 'xxx'
#to_addr = 'xxx@qq.com'
#smtp_server = 'smtp.163.com'

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication

HOST = "smtp.163.com"
SUBJECT = u"官网业务服务质量周报"
TO = "xxx@qq.com"
FROM = "xxx@163.com"

def addimg(src,imgid):
    fp = open(src, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', imgid)
    return msgImage

msg = MIMEMultipart('related')
msgtext = MIMEText("<font color=red>官网业务周平均延时图表:<br><img src=\"cid:weekly\" border=\"1\"><br>详细内容见附件。</font>","html","utf-8")
msg.attach(msgtext)
msg.attach(addimg("weekly.png","weekly"))

attach = MIMEApplication(open('曾柏超的简历.doc','rb').read())
attach.add_header('Content-Disposition', 'attachment', filename="曾柏超的简历.doc")
msg.attach(attach)




msg['Subject'] = SUBJECT
msg['From']=FROM
msg['To']=TO
try:
    server = smtplib.SMTP()
    server.connect(HOST,"25")
    server.starttls()
    server.login("xxxx@163.com","xxxx")
    server.sendmail(FROM, TO, msg.as_string())
    server.quit()
    print "邮件发送成功!"
except Exception, e:
    print "失败:"+str(e)

背景

日前不时要求出部分权且性的报表,于是就用python 的smtplib 和email
两模块写了个小程序,当数码管理完后经过邮箱把表格文件从服务器上发送出来!

EMAIL功效落成:

发送email邮件带附件,发送带附件的邮件。近来项目中提到到发送邮件效率,也参照了很多学学材质,现将Demo例子分享一下,当作记录,也使越多个人能越来越快使用.

先后名称:sendMail_func.py

一.发送EMAIL带附件,并且带压缩文件夹做为附属类小部件

本篇不涉及原理内容,如若有需求,后续补充研商.

#!/usr/bin/env python 
# -*- coding:utf-8 -*- 
import os 
import sys 
import time 
import smtplib 
from email import encoders 
from email.mime.text import MIMEText 
from email.mime.base import MIMEBase 
from email.mime.multipart import MIMEMultipart 

def send_mail(sub,content,mail_to,fileList): 
  mail_host='smtp.163.com' 
  mail_user='****@163.com' 
  mail_pass='******' 
  mail_to_list=mail_to.split(',') 

  msg = MIMEMultipart() 
  #msg=MIMEText(content,_charset='utf-8') 
  msg['Subject']=sub 
  msg['From']=mail_user 
  msg['To']=";".join(mail_to_list) 
  msg.attach(MIMEText(content,_charset='utf-8')) 

  files=fileList.split(',') 
  for f in files: 
    part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data 
    part.set_payload(open(f, 'rb').read()) 
    encoders.encode_base64(part) 
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f).encode('utf-8')) 
    msg.attach(part) 

  try: 
    s=smtplib.SMTP() 
    s.connect(mail_host) 
    s.login(mail_user,mail_pass) 
    s.sendmail(mail_user,mail_to_list,msg.as_string()) 
    s.close() 
    return True 
  except Exception, e: 
    print str(e) 
    return False 

if __name__=="__main__": 
  if len(sys.argv) == 5: 
    send_mail(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4]) 
  else: 
    print '' 
    print '*************************************************' 
    print ' Error: 请传入四个参数值:邮件主题 邮件内容 收件人 附件路径' 
    print '  如: python sendMail_func.py 邮件测试 邮件内容 abc@126.com,def@163.com,123456789@qq.com 1.xlsx,2.xlsx' 
    print '*************************************************' 
    print '' 
    exit 
#_*_coding:utf-8_*_

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.header import Header
from email import encoders
import time
import yaml,os,base64
from pos.lib import gl,scripts


class EmailClass(object):
    def __init__(self):
        self.curDateTime = str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) #当前日期时间
        self.config = scripts.getYamlfield(gl.configFile) #配置文件路径
        self.sender = self.config['EMAIL']['Smtp_Sender'] # 从配置文件获取,发件人
        self.receivers = self.config['EMAIL']['Receivers']  # 从配置文件获取,接收人
        self.msg_title = self.config['EMAIL']['Msg_Title'] #从配置文件获取,邮件标题
        self.sender_server = self.config['EMAIL']['Smtp_Server'] #从配置文件获取,发送服务器
        self.From = self.config['EMAIL']['From']
        self.To = self.config['EMAIL']['To']

    '''
    配置邮件内容
    '''
    @property
    def setMailContent(self):
        print self.receivers
        msg = MIMEMultipart()
        msg['From'] = Header(self.From,'utf-8')
        msg['To'] = self.To
        msg['Subject'] = Header('%s%s'%(self.msg_title,self.curDateTime),'utf-8')

        #附件路径
        dirpath = gl.reportPath
        zipfile = os.path.join(os.path.dirname(dirpath), 'report.zip')
        reportfile = os.path.join(gl.reportPath, 'Report.html')
        scripts.zipDir(dirpath,zipfile) #压缩报告
        #增加邮件内容为html
        fp = open(reportfile, 'rb')
        reportHtmlText = fp.read()
        msg.attach(MIMEText(reportHtmlText,'html','utf-8'))
        fp.close()

        #增加附件
        html = self.addAttach(zipfile,filename='Report%s.zip'%self.curDateTime) #自动化测试报告附件
        msg.attach(html)

        return msg


    '''
    增加附件
    '''
    def addAttach(self,apath,filename='Report.html'):
        with open(apath, 'rb') as fp:
            attach = MIMEBase('application','octet-stream')
            attach.set_payload(fp.read())
            attach.add_header('Content-Disposition', 'attachment', filename=filename)
            encoders.encode_base64(attach)
            fp.close()
            return attach


    '''
    发送电子邮件
    '''
    def sendEmail(self,message):
        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(self.sender_server,25)
            smtpObj.login(self.sender,self.config['EMAIL']['Password'])
            smtpObj.sendmail(self.sender,self.receivers , message.as_string())
            smtpObj.quit()
            print "邮件发送成功"
        except smtplib.SMTPException as ex:
            print "Error: 无法发送邮件.%s"%ex

    #发送调用
    @property
    def send(self):
        self.sendEmail(self.setMailContent)

if __name__=="__main__":
    EmailClass().send

 

上述正是本文的全体内容,希望对大家的就学抱有支持,也冀望大家多多协助脚本之家。

 

所需jar包

你只怕感兴趣的稿子:

  • python叁模块smtplib落成发送邮件作用
  • python三行使smtplib完毕发送邮件功效
  • python模块smtplib实现纯文本邮件发送作用
  • python邮件发送smtplib使用详解
  • Python
    smtplib达成出殡和埋葬邮件功用
  • python
    smtplib模块完成出殡和埋葬邮件带附属类小部件sendmail
  • python中利用smtplib和email模块发送邮件实例
  • Python
    httplib,smtplib使用格局
  • Python使用smtplib模块发送电子邮件的流程详解
  • python
    smtplib模块发送SSL/TLS安全邮件实例

相关文章