Python发送邮件(带附件)

#-*-coding:utf-8-*-

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
import smtplib
import os,datetime


time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
time_path = datetime.datetime.now().strftime('%Y-%m-%d')


# 发送邮件
def send_mail(server, fro, to, subject, htmlText, files=[]):
    try:
        msg = MIMEMultipart()
        msg['From'] = fro
        msg['Subject'] = subject
        msg['To'] = COMMASPACE.join(to)  # COMMASPACE==', '
        msg['Date'] = formatdate(localtime=True)
        # 'alternative' part, so message agents can decide which they want to display.

        msgAlternative = MIMEMultipart('alternative')
        msg.attach(msgAlternative)
        msgText = MIMEText(htmlText, 'html', 'utf-8')
        msgAlternative.attach(msgText)

        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))
            msg.attach(part)

        smtp = smtplib.SMTP(server['name'], server['port'])
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(server['user'], server['passwd'])
        smtp.sendmail(fro, to, msg.as_string())
        smtp.close()
        return True
    except Exception as e:
        print repr(e)
        return False

def export_html():
    htmlText = '''
        

您好,
  内容(请见附件)

''' htmlText += 'from who' + '

' htmlText += 'Have a good day!' return htmlText # 绝对路径 file_path = os.getcwd() + r"\\2018-03-13.xls" # 上一级os.path.join(os.path.dirname("__file__"), os.path.pardir) 再上一级就加os.path.pardir:os.path.join(os.path.dirname("__file__"), os.path.pardir,os.path.pardir) file_path = os.path.abspath(os.path.join(os.path.dirname("__file__"))) + r"\execl\%s.xls" %time_path # print file_path text = export_html() #发送人邮箱 fro = '[email protected]' #收件人邮箱和抄送 # to = ['[email protected]','[email protected]'] to = ['[email protected]'] 邮件主题 subject = u'xxxxxxxxxxxx.' mailserver_conf={'name':'发件人名称', 'user':'用户名账号', 'passwd':'密码', 'port':端口号, } send_mail(mailserver_conf,fro,to,subject,text,files=[file_path]) print '发送成功'

你可能感兴趣的:(Python发送邮件(带附件))