使用Python進行發郵件功能,
本文使用的是163郵件進行測驗,
注:163郵箱現在需要使用 客戶端授權碼 進行測驗,不再支持郵箱密碼進行測驗,
1、使用Python發Text 郵件
import smtplib # 發送字串的郵件 from email.mime.text import MIMEText # 設定服務器所需資訊 fromEmailAddr = '發件人郵箱地址' # 郵件發送方郵箱地址 password = 'email password' # 密碼(部分郵箱為授權碼) toEmailAddrs = ['接收方地址'] # 郵件接受方郵箱地址,注意需要[]包裹,這意味著你可以寫多個郵件地址群發 # 設定email資訊 # ---------------------------發送字串的郵件----------------------------- # 郵件內容設定 message = MIMEText('hello,test Python send Email.', 'plain', 'utf-8') # 郵件主題 message['Subject'] = 'python test email' # 發送方資訊 message['From'] = fromEmailAddr # 接受方資訊 message['To'] = toEmailAddrs[0] # --------------------------------------------------------------------- # 登錄并發送郵件 try: server = smtplib.SMTP('smtp.163.com') # 163郵箱服務器地址,埠默認為25 server.login(fromEmailAddr, password) server.sendmail(fromEmailAddr, toEmailAddrs, message.as_string()) print('success') server.quit() except smtplib.SMTPException as e: print("error:", e)
2、使用Python發送帶附件的郵件
import smtplib # 發送字串的郵件 from email.mime.text import MIMEText # 需要 MIMEMultipart 類 from email.mime.multipart import MIMEMultipart # 設定服務器所需資訊 fromEmailAddr = '發件人郵箱地址' # 郵件發送方郵箱地址 password = 'email password' # 密碼(部分郵箱為授權碼) toEmailAddrs = ['收件人地址'] # 郵件接受方郵箱地址,注意需要[]包裹,這意味著你可以寫多個郵件地址群發 # 設定email資訊 # ---------------------------發送帶附件郵件----------------------------- # 郵件內容設定 message = MIMEMultipart() # 郵件主題 message['Subject'] = 'python test email' # 發送方資訊 message['From'] = fromEmailAddr # 接受方資訊 message['To'] = toEmailAddrs[0] # 郵件正文內容 message.attach(MIMEText('hello,test Python send Email', 'plain', 'utf-8')) # 構造附件 att1 = MIMEText(open('text.txt', 'rb').read(), 'base64', 'utf-8') att1['Content-type'] = 'application/octet-stream' att1['Content-Disposition'] = 'attachment; filename="test.zip"' message.attach(att1) # --------------------------------------------------------------------- # 登錄并發送郵件 try: server = smtplib.SMTP('smtp.163.com') # 163郵箱服務器地址,埠默認為25 server.login(fromEmailAddr, password) server.sendmail(fromEmailAddr, toEmailAddrs, message.as_string()) print('success') server.quit() except smtplib.SMTPException as e: print("error:", e)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/211551.html
標籤:Python
上一篇:Django 檔案匯入實作方案
下一篇:Django提交時報錯
