1. 程式人生 > >python 自動傳送郵件報表,正文插入圖片,帶附件

python 自動傳送郵件報表,正文插入圖片,帶附件

# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 17:44:33 2018

@author: cp
"""

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.header import Header
import smtplib
import pandas as pd
import sys

def create_email(email_from,email_to,email_Subject,email_text,img_text,annex_path,annex_name,pic_path,pic_name):
	message = MIMEMultipart('mixed')
	
   #新增正文內容
	text = img_text +  email_text
	message.attach(MIMEText(text,"html","utf-8"))

	message["From"] = Header(email_from,"utf-8")
	message["To"] = Header(email_to,"utf-8")
	message["Subject"] = Header(email_Subject,"utf-8")
	
	#新增檔案附件
	att1 = MIMEText(open(annex_path,"rb").read(),"base64","utf-8")
	att1["Content-Type"] = "application/octet-stream"
	att1["Content-Disposition"] = "attachment;filename=" + annex_name
	message.attach(att1)
	
	#新增圖片
	att2 = MIMEImage(open(pic_path,'rb').read())
	att2.add_header('Content-ID','<image1>')
	message.attach(att2)
	return message


def send_email(sender,username,password,receiver,msg):
	try:
		print("開始連線")     
		smtp = smtplib.SMTP()
		smtp.connect('xx.xx.xx.xx',xx)
		print("連線成功")
		if username:
			smtp.login(username,password)
			print("登入成功")
		smtp.sendmail(sender,receiver,msg.as_string())
		print("郵件傳送成功!")
		smtp.quit()
	except Exception:
		print("郵件傳送失敗!")

if __name__=="__main__":		
	
	my_sender = "xxxxx"
	my_username = "xxx"
	my_password = "xxx"
	my_receiver = ["xxxxx"]
	
	my_email_from = my_sender
	my_email_to = ";".join(my_receiver)
	my_email_Subject = "每日結果分析報表"
	
	#將資料轉為html表格
	html = open(sys.argv[1],"r").read()
	my_email_text = html
	
	#將圖片插入到html檔案中
	img_text = '''
					<p>計算uv,pv:</p>
					<p><img src="cid:image1"></p>
				  '''
   #檔案附件的路徑和名稱
	my_annex_path = sys.argv[2]
	my_annex_name = sys.argv[2]
   #圖片的路徑和名稱
	pic_path = sys.argv[3]
	pic_name = sys.argv[3]
	
	my_msg = create_email(my_email_from,my_email_to,my_email_Subject,my_email_text,img_text,my_annex_path,my_annex_name,pic_path,pic_name)
	send_email(my_sender,my_username,my_password,my_receiver,my_msg)