使用Python發送各種形式的郵件的方法匯總

來源:互聯網
上載者:User
我們平時需要使用 Python 發送各類郵件,這個需求怎麼來實現?答案其實很簡單,smtplib 和 email 庫可以幫忙實現這個需求。smtplib 和 email 的組合可以用來發送各類郵件:普通文本,HTML 形式,帶附件,群發郵件,帶圖片的郵件等等。我們這裡將會分幾節把發送郵件功能解釋完成。
smtplib 是 Python 用來發送郵件的模組,email 是用來處理郵件訊息。

發送 HTML 形式的郵件
發送 HTML 形式的郵件,需要 email.mime.text 中的 MIMEText 的 _subtype 設定為 html,並且 _text 的內容應該為 HTML 形式。

import smtplibfrom email.mime.text import MIMETextsender = '***'receiver = '***'subject = 'python email test'smtpserver = 'smtp.163.com'username = '***'password = '***'msg = MIMEText(u'''

你好

''','html','utf-8')msg['Subject'] = subjectsmtp = smtplib.SMTP()smtp.connect(smtpserver)smtp.login(username, password)smtp.sendmail(sender, receiver, msg.as_string())smtp.quit()

注意:這裡的代碼並沒有把異常處理加入,需要讀者自己處理異常。

發送帶圖片的郵件
發送帶圖片的郵件是利用 email.mime.multipart 的 MIMEMultipart 以及 email.mime.image 的 MIMEImage:

import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagesender = '***'receiver = '***'subject = 'python email test'smtpserver = 'smtp.163.com'username = '***'password = '***'msgRoot = MIMEMultipart('related')msgRoot['Subject'] = 'test message'msgText = MIMEText(  ''' Some  HTML  text  and an image.good!''', 'html', 'utf-8')msgRoot.attach(msgText)fp = open('/Users/1.jpg', 'rb')msgImage = MIMEImage(fp.read())fp.close()msgImage.add_header('Content-ID', '')msgRoot.attach(msgImage)smtp = smtplib.SMTP()smtp.connect(smtpserver)smtp.login(username, password)smtp.sendmail(sender, receiver, msgRoot.as_string())smtp.quit()

發送帶附件的郵件
發送帶附件的郵件是利用 email.mime.multipart 的 MIMEMultipart 以及 email.mime.image 的 MIMEImage,重點是構造郵件標頭資訊:

import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextsender = '***'receiver = '***'subject = 'python email test'smtpserver = 'smtp.163.com'username = '***'password = '***'msgRoot = MIMEMultipart('mixed')msgRoot['Subject'] = 'test message'# 構造附件att = MIMEText(open('/Users/1.jpg', 'rb').read(), 'base64', 'utf-8')att["Content-Type"] = 'application/octet-stream'att["Content-Disposition"] = 'attachment; filename="1.jpg"'msgRoot.attach(att)smtp = smtplib.SMTP()smtp.connect(smtpserver)smtp.login(username, password)smtp.sendmail(sender, receiver, msgRoot.as_string())smtp.quit()
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.