在即時通訊軟件如此發達的今天,電子郵件仍然是互聯網上使用最爲普遍的應用之一,公司嚮應聘者發出錄用通知、網站向用戶發送一個激活帳號的連接、銀行向客戶推廣它們的理財產品等幾乎都是經過電子郵件來完成的,而這些任務應該都是由程序自動完成的。php
就像咱們能夠用HTTP(超文本傳輸協議)來訪問一個網站同樣,發送郵件要使用SMTP(簡單郵件傳輸協議),SMTP也是一個創建在TCP(傳輸控制協議)提供的可靠數據傳輸服務的基礎上的應用級協議,它規定了郵件的發送者如何跟發送郵件的服務器進行通訊的細節,而Python中的smtplib模塊將這些操做簡化成了幾個簡單的函數。python
下面的代碼演示瞭如何在Python發送郵件。git
from smtplib import SMTP from email.header import Header from email.mime.text import MIMEText def main(): # 請自行修改下面的郵件發送者和接收者 sender = 'abcdefg@126.com' receivers = ['uvwxyz@qq.com', 'uvwxyz@126.com'] message = MIMEText('用Python發送郵件的示例代碼.', 'plain', 'utf-8') message['From'] = Header('王大錘', 'utf-8') message['To'] = Header('駱昊', 'utf-8') message['Subject'] = Header('示例代碼實驗郵件', 'utf-8') smtper = SMTP('smtp.126.com') # 請自行修改下面的登陸口令 smtper.login(sender, 'secretpass') smtper.sendmail(sender, receivers, message.as_string()) print('郵件發送完成!') if __name__ == '__main__': main()
若是要發送帶有附件的郵件,那麼能夠按照下面的方式進行操做。github
from smtplib import SMTP from email.header import Header from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart import urllib def main(): # 建立一個帶附件的郵件消息對象 message = MIMEMultipart() # 建立文本內容 text_content = MIMEText('附件中有本月數據請查收', 'plain', 'utf-8') message['Subject'] = Header('本月數據', 'utf-8') # 將文本內容添加到郵件消息對象中 message.attach(text_content) # 讀取文件並將文件做爲附件添加到郵件消息對象中 with open('/Users/Hao/Desktop/hello.txt', 'rb') as f: txt = MIMEText(f.read(), 'base64', 'utf-8') txt['Content-Type'] = 'text/plain' txt['Content-Disposition'] = 'attachment; filename=hello.txt' message.attach(txt) # 讀取文件並將文件做爲附件添加到郵件消息對象中 with open('/Users/Hao/Desktop/彙總數據.xlsx', 'rb') as f: xls = MIMEText(f.read(), 'base64', 'utf-8') xls['Content-Type'] = 'application/vnd.ms-excel' xls['Content-Disposition'] = 'attachment; filename=month-data.xlsx' message.attach(xls) # 建立SMTP對象 smtper = SMTP('smtp.126.com') # 開啓安全鏈接 # smtper.starttls() sender = 'abcdefg@126.com' receivers = ['uvwxyz@qq.com'] # 登陸到SMTP服務器 # 請注意此處不是使用密碼而是郵件客戶端受權碼進行登陸 # 對此有疑問的讀者能夠聯繫本身使用的郵件服務器客服 smtper.login(sender, 'secretpass') # 發送郵件 smtper.sendmail(sender, receivers, message.as_string()) # 與郵件服務器斷開鏈接 smtper.quit() print('發送完成!') if __name__ == '__main__': main()
發送短信也是項目中常見的功能,網站的註冊碼、驗證碼、營銷信息基本上都是經過短信來發送給用戶的。在下面的代碼中咱們使用了互億無線短信平臺(該平臺爲註冊用戶提供了50條免費短信以及經常使用開發語言發送短信的demo,能夠登陸該網站並在用戶自服務頁面中對短信進行配置)提供的API接口實現了發送短信的服務,固然國內的短信平臺不少,讀者能夠根據本身的須要進行選擇(一般會考慮費用預算、短信達到率、使用的難易程度等指標),若是須要在商業項目中使用短信服務建議購買短信平臺提供的套餐服務。web
import urllib.parse
import http.client import json def main(): host = "106.ihuyi.com" sms_send_uri = "/webservice/sms.php?method=Submit" # 下面的參數須要填入本身註冊的帳號和對應的密碼 params = urllib.parse.urlencode({'account': '你本身的帳號', 'password' : '你本身的密碼', 'content': '您的驗證碼是:147258。請不要把驗證碼泄露給其餘人。', 'mobile': '接收者的手機號', 'format':'json' }) print(params) headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'} conn = http.client.HTTPConnection(host, port=80, timeout=30) conn.request('POST', sms_send_uri, params, headers) response = conn.getresponse() response_str = response.read() jsonstr = response_str.decode('utf-8') print(json.loads(jsonstr)) conn.close() if __name__ == '__main__': main()