標籤:sage 1.5 測試 alt 關閉 51cto send too [1]
python發送郵件
1.通過python發郵件步驟:
前提:開通了第三方授權,可以使用smtp服務
1.建立smtp對象
2.串連smtp伺服器,預設連接埠號碼都是25
3.登陸自己的郵箱帳號
4.調用發送訊息函數,參數:寄件者、收件者、訊息內容
5.關閉串連
2.郵件訊息註冊:
首先建立一個訊息對象:
msg = email.mime.multipart.MIMEMultipart() #通過這個類建立訊息
msg['from'] = '[email protected]'
msg['to'] = '[email protected];[email protected];[email protected]'
msg['subject'] = 'aji111‘
分別指明郵件的寄件者,收件, 只代表顯示的問題,如:
3.訊息內容:
首先,先定義一個字串,來表示你得訊息內容:
context= ‘’’hello world’’’ ## 本文
txt = email.mime.text.MIMEText(_text=content, _subtype="html")## 定義文本以後,標明將context指定成什麼格式,html,txt
msg.attach(txt)## 再註冊到訊息中
_subtype 這個參數就決定了,你是以html解析的形式去發送,還是以text的形式去發送。
準備檔案:
(1)測試組態檔案:
檔案1:message.conf(設定檔)
From = [email protected]To = [email protected],[email protected],[email protected],[email protected],[email protected]Subject = '測試郵件'message = '''大家好:測試郵件測試郵件以上謝謝'''
(2)讀取檔案conf檔案工具,並測試
檔案2:util.py(工具檔案)
import codecsimport refileName = "message.conf"def getProperty(property): with codecs.open(fileName, encoding="utf-8") as f: if property != "message": for line in f.readlines(): if line.startswith("{0} = ".format(property)): value = line.split("{0} = ".format(property))[1] print value.strip('\n') return value.strip('\n') else: reg = re.compile(r"message = '''((.*\n)*)'''") result = reg.findall(f.read()) print result[0][0] return result[0][0]getProperty("From")getProperty("To")getProperty("Subject")getProperty("message")
檔案2 調用 檔案1 的參數,獲得到對應的值,測試結果
測試完成後,登出輸出資訊和調用函數
(3)發送郵件指令碼
3.檔案:sendtext.py (郵件指令檔)
import email.mime.multipartimport email.mime.textimport email.headerfrom util import getPropertyimport smtplib#訊息內容msg = email.mime.multipart.MIMEMultipart()sendFrom = getProperty("From")sendTo = getProperty("To")sendSubject = getProperty("Subject")sendMessage = getProperty("message")msg["From"] = sendFrommsg["To"] = sendTomsg['Subject'] = email.header.Header(sendSubject)text = email.mime.text.MIMEText(sendMessage, 'plain', 'utf-8')msg.attach(text)#發送smtp = smtplib.SMTP_SSL("smtp.qq.com", 465)smtp.login('[email protected]', 'xrusbcaae')smtp.sendmail(sendFrom, sendTo.split(","), msg.as_string())smtp.quit()
執行發送郵件:
48. Python 發郵件(1)