python郵箱傳送四位數隨機驗證碼
阿新 • • 發佈:2021-07-15
import smtplib from email.mime.text import MIMEText from email.utils import formataddr import random def mail(my_user): my_sender = '[email protected]' # 發件人郵箱賬號 my_pass = 'dzbjszuybbhc' # 發件人郵箱的授權碼 my_user = my_user # 收件人郵箱賬號,我這邊傳送給自己 ret= True try: num = random.randint(1000,9999) msg = MIMEText('驗證碼為:{}'.format(num), '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() # 關閉連線 return ret, my_user, num except Exception as e: # 如果 try 中的語句沒有執行,則會執行下面的ret=False ret= False return ret ret,my_user,num = mail("[email protected]") if ret: print("郵件傳送成功") print(my_user,num) else: print("郵件傳送失敗")