21-py3 發郵件

來源:互聯網
上載者:User

標籤:protoc   失敗   引入   receive   exception   服務   tps   class   int   

Python3 SMTP發送郵件

SMTP(Simple Mail Transfer Protocol)即簡易郵件傳輸通訊協定,它是一組用於由源地址到目的地址傳送郵件的規則,由它來控制信件的中轉方式。

python的smtplib提供了一種很方便的途徑寄送電子郵件。它對smtp協議進行了簡單的封裝。

Python建立 SMTP 對象文法如下:

import smtplibsmtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

參數說明:

  • host: SMTP 伺服器主機。 你可以指定主機的ip地址或者網域名稱如:runoob.com,這個是選擇性參數。
  • port: 如果你提供了 host 參數, 你需要指定 SMTP 服務使用的連接埠號碼,一般情況下SMTP連接埠號碼為25。
  • local_hostname: 如果SMTP在你的本機上,你只需要指定伺服器位址為 localhost 即可。

Python SMTP對象使用sendmail方法發送郵件,文法如下:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]

參數說明:

  • from_addr: 郵件寄件者地址。
  • to_addrs: 字串列表,郵件發送地址。
  • msg: 發送訊息

這裡要注意一下第三個參數,msg是字串,表示郵件。我們知道郵件一般由標題,發信人,收件者,郵件內容,附件等構成,發送郵件的時候,要注意msg的格式。這個格式就是smtp協議中定義的格式。

執行個體
import smtplibfrom email.header import Header  # 用來設定郵件標頭和郵件主題from email.mime.text import MIMEText  # 發送本文只包含簡單文本的郵件,引入MIMEText即可import time# 所使用的用來發送郵件的SMTP伺服器smtpServer = ‘smtp.qq.com‘# 發送郵箱的使用者名稱和授權碼(不是登入郵箱的密碼)username = ‘[email protected]‘password = ‘xxxxxxxxx‘# 寄件者和收件者sender = ‘[email protected]‘receiver = ‘[email protected]‘#發送的題目和內容mail_title = ‘ystraw‘mail_body = ‘祝您愉快‘# 建立一個執行個體message = MIMEText(mail_body, ‘plain‘, ‘utf-8‘)  # 郵件內文message[‘From‘] = sender  # 郵件上顯示的寄件者message[‘To‘] = receiver  # 郵件上顯示的收件者message[‘Subject‘] = Header(mail_title, ‘utf-8‘)  # 郵件主題try:    smtp = smtplib.SMTP()  # 建立一個串連    smtp.connect(smtpServer)  # 串連發送郵件的伺服器    smtp.login(username, password)  # 登入伺服器    ct = 10 #發送次數    for i in range(ct):        smtp.sendmail(sender, receiver, message.as_string())  # 填入郵件的相關資訊並發送        time.sleep(5)  # 停留5秒        print(i)    print("郵件發送成功!!!")    smtp.quit()  #關閉串連except smtplib.SMTPException:    print("郵件發送失敗!!!")

  

21-py3 發郵件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.