python 發送郵件----正文內容:文字、表格、附件
阿新 • • 發佈:2019-03-15
lpad 解決亂碼 list gin log 失敗 blog htm position
python 發送郵件----正文內容包含:文字、表格、附件
python 發送郵件----正文內容包含:文字、表格、附件
import pandas as pd import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart filename=‘C:\\Users\\thinkpad\\Desktop\\1.xlsx‘ #附件地址 def send_mail(to_list,sub,context,filename): #to_list:收件人;sub:主題;content:郵件內容mail_host="smtp.163.com" #設置服務器 mail_user="[email protected]" #用戶名 mail_pass="xxxxxx" #口令 mail_postfix="163.com" #發件箱的後綴 me="服務器"+"<"+mail_user+"@"+mail_postfix+">" #這裏的“服務器”可以任意設置,收到信後,將按照設置顯示 msg = MIMEMultipart() #給定msg類型 msg[‘Subject‘] = sub #郵件主題 msg[‘From‘] = me msg[‘To‘] = ";".join(mailto_list) msg.attach(context)
#構造附件1 att1 = MIMEText(open(filename, ‘rb‘).read(), ‘xls‘, ‘gb2312‘) att1["Content-Type"] = ‘application/octet-stream‘ att1["Content-Disposition"] = ‘attachment;filename=‘+filename[-6:]#這裏的filename可以任意寫,寫什麽名字,郵件中顯示什麽名字,filename[-6:]指的是之前附件地址的後6位msg.attach(att1) try: s = smtplib.SMTP() s.connect(mail_host) #連接smtp服務器 s.login(mail_user,mail_pass) #登陸服務器 s.sendmail(me, mailto_list, msg.as_string()) #發送郵件 s.close() return True except Exception: return False
if __name__ == ‘__main__‘: mailto_list=["[email protected]"] a=pd.DataFrame({‘數列1‘:(1,1,1,1),‘數列2‘:(2,2,2,2),‘數列3‘:(3,3,3,3),‘數列4‘:(4,4,4,4)}) a.index={‘行1‘,‘行2‘,‘行3‘,‘行4‘} #這裏dataframe類型a就是要輸出的表格 sub="test" d=‘‘ #表格內容 for i in range(len(a)): d=d+""" <tr> <td>""" + str(a.index[i]) + """</td> <td>""" + str(a.iloc[i][0]) + """</td> <td width="60" align="center">""" + str(a.iloc[i][1]) + """</td> <td width="75">""" + str(a.iloc[i][2]) + """</td> <td width="80">""" + str(a.iloc[i][3]) + """</td> </tr>""" html = """<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <body> <div id="container"> <p><strong>測試程序郵件發送:</strong></p> <div id="content"> <table width="30%" border="2" bordercolor="black" cellspacing="0" cellpadding="0"> <tr> <td width="40"><strong>統計</strong></td> <td width="50"><strong>數列1</strong></td> <td width="60" align="center"><strong>數列2</strong></td> <td width="50"><strong>數列3</strong></td> <td width="80"><strong>數列4</strong></td> </tr>"""+d+""" </table> </div> </div> </div> </body> </html> """
context = MIMEText(html,_subtype=‘html‘,_charset=‘utf-8‘) #解決亂碼 if send_mail(mailto_list,sub,context,filename): print ("發送成功") else: print( "發送失敗")
原文地址https://blog.csdn.net/u010199776/article/details/76087721
python 發送郵件----正文內容:文字、表格、附件