Python菜譜7:發(fā)送混合郵件

2018-07-25 18:20 更新

我們平時需要使用 Python 發(fā)送各類郵件,這個需求怎么來實現(xiàn)?答案其實很簡單,smtplib 和 email庫可以幫忙實現(xiàn)這個需求。smtplib 和 email 的組合可以用來發(fā)送各類郵件:普通文本,HTML 形式,帶附件,群發(fā)郵件,帶圖片的郵件等等。我們這里將會分幾節(jié)把發(fā)送郵件功能解釋完成。

smtplib 是 Python 用來發(fā)送郵件的模塊,email 是用來處理郵件消息。

發(fā)送郵件系列最后一篇將會介紹發(fā)送混合郵件:里面包含附件,HTML 形式,不同文本:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = "Link"

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\

Hi!

 How are you?

 Here is the link you wanted.

"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# 構(gòu)造附件
att = MIMEText(open('/Users/1.jpg', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="1.jpg"'
msg.attach(att)

smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

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

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號