1. 程式人生 > >python3之發送郵件

python3之發送郵件

python 郵件

#/usr/bin/env python3
# encoding: utf-8
[email protected]: Lejie
[email protected]: PyCharm Community Edition
[email protected]: learn_smtp.py
[email protected]: 2017/6/26 16:29


import smtplib
import email.mime.multipart
import email.mime.text
from email.mime.application import MIMEApplication

msg = email.mime.multipart.MIMEMultipart()   #定義郵件對象
# print(msg,type(msg))

msg[‘from‘] = [email protected]
/* */ #必須和login的賬號一樣 msg[‘to‘] = [email protected],[email protected] msg[‘subject‘] = ‘test‘ #郵件內容 ###直接定義 content = ‘‘‘ 你好, 這是一封測試郵件。 ‘‘‘ ###從文件讀取內容 content1 = open(‘tt.log‘,‘rb‘).read() #以rb來讀取文件內容,可以識別中文 ###插入文本 txt = email.mime.text.MIMEText(content1,‘html‘,‘utf-8‘) #html 類型 # txt = email.mime.text.MIMEText(content1,‘plain‘,‘utf-8‘) #txt類型 msg.attach(txt) #文本附件 MIMEText ,這種方式文本內容會在顯示在郵件內容裏 # att1 = email.mime.text.MIMEText(open(‘tt.log‘, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) # att1["Content-Type"] = ‘application/octet-stream‘ # att1["Content-Disposition"] = ‘attachment;filename="test.txt"‘ # msg.attach(att1) #添加附件 MIMEApplication 支持大部分圖片格式,pdf,excel,mp3,txt等等 att2 = MIMEApplication(open(‘tt.log‘,‘rb‘).read()) #filename指定的名字跟實體文件名沒有關系可以任意指定 att2.add_header(‘Content-Disposition‘,‘attachment‘,filename="t.log") msg.attach(att2) # #配置smtp smtp = smtplib # smtp = smtplib.SMTP() #不加密 # smtp.connect(‘smtp.exmail.qq.com‘, ‘25‘) smtp = smtplib.SMTP_SSL() #加密 smtp.connect(‘smtp.exmail.qq.com‘, ‘465‘) try: #驗證 smtp.login([email protected]
/* */, [email protected]) #發送 smtp.send_message(msg) #不用指定from,to # smtp.sendmail([email protected], [email protected], str(msg)) #必須指定from,to print("發送成功") except Exception as e: print(e) smtp.quit()


python3之發送郵件