python菜谱发送到邮箱_Python菜谱5:发送带附件的邮件
我們平時需要使用 Python 發送各類郵件,這個需求怎么來實現?答案其實很簡單,smtplib?和?email庫可以幫忙實現這個需求。smtplib?和?email?的組合可以用來發送各類郵件:普通文本,HTML 形式,帶附件,群發郵件,帶圖片的郵件等等。我們這里將會分幾節把發送郵件功能解釋完成。
smtplib?是 Python 用來發送郵件的模塊,email?是用來處理郵件消息。
發送帶附件的郵件是利用 email.mime.multipart 的 MIMEMultipart 以及 email.mime.image 的 MIMEImage,重點是構造郵件頭信息:
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 = '***'
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()
注意:這里的代碼并沒有把異常處理加入,需要讀者自己處理異常。
總結
以上是生活随笔為你收集整理的python菜谱发送到邮箱_Python菜谱5:发送带附件的邮件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 更改应用程序图标_【iOS12人机交互指
- 下一篇: 同花顺怎么导出数据到excel_Exce