此文章github地址:https://github.com/GhostCNZ/Python_sendEmail
使用Python內置的smtplib包和email包來實現郵件的構造和發送。
發送純文本時:
1.需要導入Python3標准庫中的smtplib包和email包來實現郵件的構造和發送。
import smtplib # 發送字符串的郵件 from email.mime.text import MIMEText # 處理多種形態的郵件主體需要 MIMEMultipart 類 from email.mime.multipart import MIMEMultipart # 處理圖片需要 MIMEImage 類 from email.mime.image import MIMEImage
2.配置郵件發送及接收人
fromaddr = '1oo88@sina.cn' # 郵件發送方郵箱地址 password = '******' # 密碼(部分郵箱為授權碼) toaddrs = ['1oo88@sina.cn', '1951995428@qq.com'] # 郵件接受方郵箱地址,注意需要[]包裹,這意味着可以寫多個郵件地址群發
3.內容
#郵件內容設置 message = MIMEText('Python發郵件測試', 'plain', 'utf-8') #郵件主題 message['Subject'] = '測試' #發送方信息 message['From'] = fromaddr #接受方信息 message['To'] = toaddrs[0]
4.登錄並發送
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) # 打印錯誤
發送帶有附件時:
1.設置email信息
#添加一個MIMEmultipart類,處理正文及附件 message = MIMEMultipart() message['From'] = fromaddr message['To'] = toaddrs[0] message['Subject'] = 'title'
推薦使用html格式的正文內容,這樣比較靈活,可以附加圖片地址,調整格式等
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"'
2.將內容添加到郵件主體中
message.attach(part1)
message.attach(part2)
message.attach(picture)
3.登錄並發送
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,解決辦法為:
#啟動 smtpObj = smtplib.SMTP() #連接到服務器 smtpObj.connect(mail_host,25) #######替換為######## smtpObj = smtplib.SMTP_SSL(mail_host)