1. 程式人生 > 其它 >通過smtplib和email傳送驗證碼到電子郵箱(Python3.7.X)

通過smtplib和email傳送驗證碼到電子郵箱(Python3.7.X)

技術標籤:python

使用前需要在傳送方的郵箱裡開啟POP3/SMTP服務,這裡以QQ郵箱為例,設定——賬戶——開啟服務——獲得授權碼,以下案例模擬傳送一串純文字的6位數字驗證碼,比較簡單易懂,可在此基礎上再完善。

效果演示:
在這裡插入圖片描述
程式碼展示:

# coding=utf-8
import smtplib
import string
import random
from email.mime.text import MIMEText

msg_from = '此處填寫開啟SMTP服務的郵箱'  # 傳送方郵箱
passwd = '此處填寫自己的授權碼'  # 就是上面的授權碼
to_mail =
input("請輸入要傳送的郵箱地址:") to = [to_mail] # 設定郵件內容 num = string.digits def update_num(): num_digits = "" for i in range(6): num1 = random.choice(num) num_digits = num_digits + num1 return num_digits content = "驗證碼: " + "<font color='orange' size='5px'><b>"
+ update_num() + "</b></font>" # 把內容加進去 msg = MIMEText(content, 'html', 'utf-8') # 設定郵件主題 msg['Subject'] = "郵箱驗證" # 傳送方資訊 msg['From'] = msg_from # 開始傳送 # 通過SSL方式傳送,伺服器地址和埠 try: s = smtplib.SMTP_SSL("smtp.qq.com", 465) # 登入郵箱 s.login(msg_from, passwd)
# 開始傳送 s.sendmail(msg_from, to, msg.as_string()) s.quit() print("郵件傳送成功") except Exception as e: print(e)

不足之處:
1、驗證碼傳送後沒有驗證過期的時間
2、沒有對輸入的郵箱有效性的驗證判斷