1. 程式人生 > >python學習筆記23(利用python發郵件和簡訊)

python學習筆記23(利用python發郵件和簡訊)

利用python發郵件和簡訊

發郵件: 以163郵箱為例,要利用SMTP伺服器

#發郵件的庫
import smtplib
#郵件文字
from email.mime.text import MIMEText

#建立基礎物件
#SMTP伺服器
SMTPServer = "smtp.163.com"
#發郵件的地址
sender = "********@163.com"
#傳送者郵箱的密碼
passwd = "********"

#建立郵件物件
#設定傳送的內容
message = "sunck is a good man"
#轉換成郵件文字
msg = MIMEText(message)
#標題
msg["Subject"] = "來自帥哥的問候"
#傳送者
msg["From"] = sender

#運用上面的物件完成發郵件的功能
#建立SMTP伺服器
mailServer = smtplib.SMTP(SMTPServer, 25)
#登陸郵箱
mailServer.login(sender, passwd)
#傳送郵件
mailServer.sendmail(sender, ["
[email protected]
"], msg.as_string()) #退出郵箱 mailServer.quit()

發簡訊驗證碼: 以互億無線為例

# 介面型別:互億無線觸發簡訊介面,支援傳送驗證碼簡訊、訂單通知簡訊等。
# 賬戶註冊:請通過該地址開通賬戶http://sms.ihuyi.com/register.html
# 注意事項:
# (1)除錯期間,請用預設的模板進行測試,預設模板詳見介面文件;
# (2)請使用APIID(檢視APIID請登入使用者中心->驗證碼簡訊->產品總覽->APIID)及 APIkey來呼叫介面;
# (3)該程式碼僅供接入互億無線簡訊介面參考使用,客戶可根據實際需要自行編寫;

# !/usr/local/bin/python
# -*- coding:utf-8 -*-
import http.client
import urllib

#建立基礎資訊物件
host = "106.ihuyi.com"
sms_send_uri = "/webservice/sms.php?method=Submit"
# 使用者名稱是登入使用者中心->驗證碼簡訊->產品總覽->APIID
account = "**********"
# 密碼 檢視密碼請登入使用者中心->驗證碼簡訊->產品總覽->APIKEY
password = "****************"

#建立任務物件
def send_sms(text, mobile):
    params = urllib.parse.urlencode(
        {'account': account, 'password': password, 'content': text, 'mobile': mobile, 'format': 'json'})
    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()
    conn.close()
    return response_str

#如果是直接執行則執行主程式中的任務
if __name__ == '__main__':
    mobile = "12345678900"    #電話號可改
    text = "您的驗證碼是:123456。請不要把驗證碼洩露給其他人。"    #驗證碼的數字可改,文字內容不可改

    print(send_sms(text, mobile))