sendmail-attachment.py——發送帶附件的郵件

#!/usr/bin/env pythonhtml

#coding:utf-8python

import smtplibapp

from email.mime.multipart import MIMEMultipartide

from email.mime.text import MIMETextui

from email.mime.p_w_picpath import MIMEImage編碼

HOST = "smtp.126.com"code

SUBJECT = u"官網業務服務質量週報"server

TO = "to@qq.com"htm

FROM = "from@126.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("img/weekly.png", "weekly"))

# 建立一個MIMEText對象,附加week_report.xlsx文檔

attach = MIMEText(open("doc/week_report.xlsx", "rb").read(), "base64", "utf-8")

attach["Content-Type"] = "application/octet-stream"    # 指定文件格式類型

# 指定Content-Disposition值爲p_w_upload則出現下載保存對話框,保存的默認文件名使用filename指定

# 因爲qqmail使用gb18030頁面編碼,爲保證中文文件名不出現亂碼,對文件名進行編碼轉換

attach["Content-Disposition"] = "p_w_upload; filename=\"業務服務質量週報(12周).xlsx\"".decode("utf-8").encode("gb18030")

msg.attach(attach)

msg['Subject'] = SUBJECT

msg['From'] = FROM

msg['To'] = TO

try:

    server = smtplib.SMTP(HOST, "25")

    server.starttls()

    server.login("from@126.com", "passwd")

    server.sendmail(FROM, TO, msg.as_string())

    server.quit()

    print "郵件發送成功!"

except Exception, e:

    print "失敗: "+str(e)

相關文章
相關標籤/搜索