腳本:html
#!/usr/bin/python3 # purpose:send_mail # write by:wang # date:2019-06-18 from email.mime.text import MIMEText import smtplib from email import encoders from email.header import Header from email.utils import parseaddr,formataddr from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage # 定義format_addr()函數格式化郵件地址 # parseaddr()用於解析字符串中的email地址。 # 若是包含中文對象,要用Header對象進行編碼 # encode()編碼,decode()解碼 def format_addr(s): name,addr = parseaddr(s) return formataddr((Header(name,'utf-8').encode(),addr)) # with open .....as .... 相似於try.....finally # 打開文件用open() # f.close()文件使用完畢後必須關閉 # r表示文本文件,rb表示二進制文件 # python讀文件方法 read()、readline() 和 readlines() # 上述三種方法會默認把每行末尾的\n讀取出來,可是使用print()時不會顯示\n,在print()中\n表示換行。 # strip()能夠去掉\n # 列表元素下標默認從0開始 # try: # f = open('/wh_k/scripts/email_information.txt','r') # finally: # if f: # f.close() with open('/wh_k/scripts/email_information.txt', 'r') as f: info_list = f.readlines() from_addr = info_list[0].strip('\n') password = info_list[1].strip('\n') to_addr = info_list[2].strip('\n') smtp_server = info_list[3].strip('\n') # MIMEMultipart()建立一個帶附件的實例 # msg['To']接收的是字符串而不是list,若是有多個郵件地址,用,分隔便可 msg = MIMEMultipart() msg['From'] = format_addr('139郵箱<%s>' % from_addr) msg['To'] = format_addr('QQ郵箱<%s>' % to_addr) msg['Subject'] = Header('來自139的測試','utf-8').encode() # 發送純文本郵件 # plain表示純文本郵件, # msg.attach(MIMEText('This is a test mail.','plain','utf-8')) # 發送附件1 # base64表示編碼 # Content-*添加頭信息 # filename能夠任意寫,寫什麼名字,郵件中就顯示什麼名字 mime1 = MIMEText(open('/wh_k/scripts/downloads/test.png', 'rb').read(), 'base64', 'utf-8') mime1["Content-Type"] = 'application/octet-stream' mime1["Content-Disposition"] = 'attachment; filename="test.png"' msg.attach(mime1) # 發送HTML郵件,帶連接 # 發送html郵件時,構造MIMEText對象,把HTML字符串傳進去,再把第二個參數由plain變爲html # 發送HTML郵件中帶圖片原理,將圖片構建成附件,經過cid引用 msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) msgAlternative.attach(MIMEText('<html><body><h1>Test picture</h1>'+ '<p>send by <a href="http://www.139.com">139郵箱</a>...</p>'+ '<p><img src="cid:image1"></p>'+ '</body></html>', 'html', 'utf-8')) # 指定圖片爲當前目錄 fp = open('/wh_k/scripts/downloads/test.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() # 定義圖片ID,在HTML文本中引用 msgImage.add_header('Content-ID', '<image1>') msg.attach(msgImage) #SMTP協議默認端口是25. #set_debuglevel(1)就能夠打印出和SMTP服務器交互的全部信息 #sendmail()方法就是發郵件,因爲能夠一次發給多我的,因此傳入一個list #郵件正文是一個str,as_string()把MIMEText對象變成str server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr,password) server.sendmail(from_addr,[to_addr],msg.as_string()) server.quit()