此文章github地址:https://github.com/GhostCNZ/Python_sendEmailhtml
使用Python內置的smtplib包和email包來實現郵件的構造和發送。git
import smtplib # 發送字符串的郵件 from email.mime.text import MIMEText # 處理多種形態的郵件主體須要 MIMEMultipart 類 from email.mime.multipart import MIMEMultipart # 處理圖片須要 MIMEImage 類 from email.mime.image import MIMEImage
fromaddr = '1oo88@sina.cn' # 郵件發送方郵箱地址 password = '******' # 密碼(部分郵箱爲受權碼) toaddrs = ['1oo88@sina.cn', '1951995428@qq.com'] # 郵件接受方郵箱地址,注意須要[]包裹,這意味着能夠寫多個郵件地址羣發
#郵件內容設置 message = MIMEText('Python發郵件測試', 'plain', 'utf-8') #郵件主題 message['Subject'] = '測試' #發送方信息 message['From'] = fromaddr #接受方信息 message['To'] = toaddrs[0]
try: server = smtplib.SMTP('smtp.sina.cn') # sina郵箱服務器地址,端口默認爲25 server.login(fromaddr, password) server.sendmail(fromaddr, toaddrs, message.as_string()) print('success') server.quit() except smtplib.SMTPException as e: print('error', e) # 打印錯誤
#添加一個MIMEmultipart類,處理正文及附件 message = MIMEMultipart() message['From'] = fromaddr message['To'] = toaddrs[0] message['Subject'] = 'title'
推薦使用html格式的正文內容,這樣比較靈活,能夠附加圖片地址,調整格式等github
with open('abc.html','r') as f: content = f.read() #設置html格式參數 part1 = MIMEText(content,'html','utf-8')
添加txt文本格式內容服務器
#添加一個txt文本附件 with open('abc.txt','r')as h: content2 = h.read() #設置txt參數 part2 = MIMEText(content2,'plain','utf-8') #設置附件頭,添加文件名 part2['Content-Disposition'] = 'attachment;filename="abc.txt"'
添加照片附件併發
#添加照片附件 with open('1.png','rb')as fp: picture = MIMEImage(fp.read()) #與txt文件設置類似 picture['Content-Type'] = 'application/octet-stream' picture['Content-Disposition'] = 'attachment;filename="1.png"'
message.attach(part1) message.attach(part2) message.attach(picture)
try: smtpObj = smtplib.SMTP() smtpObj.connect('smtp.sina.cn',25) smtpObj.login(fromaddr,password) smtpObj.sendmail( fromaddr,toaddrs,message.as_string()) print('success') smtpObj.quit() except smtplib.SMTPException as e: print('error',e)
一些郵箱登陸好比 QQ 郵箱須要 SSL 認證,因此 SMTP 已經不能知足要求,而須要SMTP_SSL,解決辦法爲:app
#啓動 smtpObj = smtplib.SMTP() #鏈接到服務器 smtpObj.connect(mail_host,25) #######替換爲######## smtpObj = smtplib.SMTP_SSL(mail_host)