##python 發郵件(smtplib)
阿新 • • 發佈:2018-12-29
# !/usr/bin/python # -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.utils import formataddr my_sender = '[email protected]' # 發件人郵箱賬號 my_pass = 'npchvesspjcwbjji' # 發件人郵箱密碼 my_user = '[email protected]' # 收件人郵箱賬號,我這邊傳送給自己 def mail(): ret = True try: msg = MIMEText('hello wored', 'plain', 'utf-8') msg['From'] = formataddr(["caojunliang", my_sender]) # 括號裡的對應發件人郵箱暱稱、發件人郵箱賬號 msg['To'] = formataddr(["cjl", my_user]) # 括號裡的對應收件人郵箱暱稱、收件人郵箱賬號 msg['Subject'] = "郵件測試" # 郵件的主題, server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 發件人郵箱中的SMTP伺服器,埠是465 server.login(my_sender,my_pass) # 括號中對應的是發件人郵箱賬號、郵箱密碼 server.sendmail(my_sender, [my_user, ], msg.as_string()) # 括號中對應的是發件人郵箱賬號、收件人郵箱賬號(可以是多個人(list))、傳送郵件 server.quit() # 關閉連線 except Exception: # 如果 try 中的語句沒有執行,則會執行下面的 ret=False ret = False return ret ret = mail() if ret: print("郵件傳送成功") else: print("郵件傳送失敗")
這裡的密碼不是QQ密碼,是要去郵箱裡設定.