Python3實現發送郵件和發送短信驗證碼

 

Python3實現發送郵件和發送短信驗證碼

 

Python3實現發送郵件:

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

my_sender = '1434399884@qq.com'  # 發件人郵箱帳號
my_pass = '*********'  # 發件人郵箱的受權碼
my_user = '3152609963@qq.com'  # 收件人郵箱帳號,我這邊發送給本身


def mail():
    ret= True
    try:
        msg = MIMEText('驗證碼爲:123456', 'plain', 'utf-8')
        msg['From'] = formataddr(["From nicead.top", my_sender]) # 括號裏的對應發件人郵箱暱稱、發件人郵箱帳號
        msg['To'] = formataddr(["FK", my_user]) # 括號裏的對應收件人郵箱暱稱、收件人郵箱帳號
        msg['Subject'] = "驗證碼" # 郵件的主題,也能夠說是標題
        server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 發件人郵箱中的SMTP服務器,端口是25
        server.login(my_sender, my_pass) # 括號中對應的是發件人郵箱帳號、郵箱密碼
        server.sendmail(my_sender, [my_user, ], msg.as_string()) # 括號中對應的是發件人郵箱帳號、收件人郵箱帳號、發送郵件
        server.quit()  # 關閉鏈接
    except Exception as e:  # 若是 try 中的語句沒有執行,則會執行下面的ret=False
        ret = False
    return ret
ret = mail()
if ret:
    print("郵件發送成功")
else:
    print("郵件發送失敗")

 

 

注意受權碼:須要在郵件中的設置中獲取,如QQ郵箱獲取受權碼的方法:php

 

 

 

 

 

 

 

 

 

 

 Python3實現短信驗證碼

 

# 接口類型:互億無線觸發短信接口,支持發送驗證碼短信、訂單通知短信等。
# 帳戶註冊:請經過該地址開通帳戶http://sms.ihuyi.com/register.html
# 注意事項:
# (1)調試期間,請使用用系統默認的短信內容:您的驗證碼是:【變量】。請不要把驗證碼泄露給其餘人。;
# (2)請使用APIID(查看APIID請登陸用戶中心->驗證碼短信->產品總覽->APIID)及 APIkey來調用接口;
# (3)該代碼僅供接入互億無線短信接口參考使用,客戶可根據實際須要自行編寫;
#發送短信
#APIID:C11345804
#APIKEY:735d183ae02189f678c26800ac19b03a

# !/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 = "手機號"
  #短信內容
text = "您的驗證碼是:121254。請不要把驗證碼泄露給其餘人。" ret = send_sms(text, mobile).decode('utf-8') import json ret = json.loads(ret) print(ret)

 

 

 注意:html

# 用戶名是登陸用戶中心->驗證碼短信->產品總覽->APIID account = "************" # 密碼 查看密碼請登陸用戶中心->驗證碼短信->產品總覽->APIKEY password = "**********************"

 須要在互億無線觸發短信接口的官網註冊一個帳號,會提供免費發送十次短信驗證碼。http://sms.ihuyi.com/register.htmlpython

相關文章
相關標籤/搜索