在即時通信軟件如此發達的今天,電子郵件仍然是互聯網上使用最爲廣泛的應用之一,公司向應聘者發出錄用通知、網站向用戶發送一個激活賬號的鏈接、銀行向客戶推廣它們的理財産品等幾乎都是通過電子郵件來完成的,而這些任務應該都是由程序自動完成的。
就像我們可以用HTTP(超文本傳輸協議)來訪問一個網站一樣,發送郵件要使用SMTP(簡單郵件傳輸協議),SMTP也是一個建立在TCP(傳輸控制協議)提供的可靠數據傳輸服務的基礎上的應用級協議,它規定了郵件的發送者如何跟發送郵件的服務器進行通信的細節,而Python中的smtplib模塊將這些操作簡化成了幾個簡單的函數。
下面的代碼演示了如何在Python發送郵件。
from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText
def main():
# 請自行修改下面的郵件發送者和接收者
sender = '[email protected]'
receivers = ['[email protected]', '[email protected]']
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()
如果要發送帶有附件的郵件,那麽可以按照下面的方式進行操作。
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 = '[email protected]'
receivers = ['[email protected]']
# 登錄到SMTP服務器
# 請注意此處不是使用密碼而是郵件客戶端授權碼進行登錄
# 對此有疑問的讀者可以聯係自己使用的郵件服務器客服
smtper.login(sender, 'secretpass')
# 發送郵件
smtper.sendmail(sender, receivers, message.as_string())
# 與郵件服務器斷開連接
smtper.quit()
print('發送完成!')
if __name__ == '__main__':
main()
發送短信也是項目中常見的功能,網站的注冊碼、驗證碼、營銷信息基本上都是通過短信來發送給用戶的。在下面的代碼中我們使用了互億無線短信平台(該平台爲注冊用戶提供了50條免費短信以及常用開發語言發送短信的demo,可以登錄該網站並在用戶自服務頁面中對短信進行配置)提供的API接口實現了發送短信的服務,當然國內的短信平台很多,讀者可以根據自己的需要進行選擇(通常會考慮費用預算、短信達到率、使用的難易程度等指標),如果需要在商業項目中使用短信服務建議購買短信平台提供的套餐服務。
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()