欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python2.7實(shí)現(xiàn)郵件發(fā)送功能

 更新時(shí)間:2018年12月12日 11:11:05   作者:Lockeyi  
這篇文章主要為大家詳細(xì)介紹了python2.7實(shí)現(xiàn)郵件發(fā)送功能包,含文本、附件、正文圖片等,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

要想實(shí)現(xiàn)一個(gè)能夠發(fā)送帶有文本、圖片、附件的python程序,首先要熟悉兩大模塊:

email以及smtplib

然后對(duì)于MIME(郵件擴(kuò)展)要有一定認(rèn)知,因?yàn)橛辛藬U(kuò)展才能發(fā)送附件以及圖片這些媒體或者非文本信息

最后一個(gè)比較細(xì)節(jié)的方法就是MIMEMultipart,要理解其用法以及對(duì)應(yīng)參數(shù)所實(shí)現(xiàn)的功能區(qū)別

發(fā)送郵件三部曲:

創(chuàng)建協(xié)議對(duì)象
連接郵件服務(wù)器
登陸并發(fā)送郵件

from email.header import Header
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
import mimetypes

from email.mime.multipart import MIMEMultipart
import os
import smtplib

from email import Encoders as email_encoders


class Message(object):
 def __init__(self, from_addr, to_addr, subject="", html="", text=None, cc_addr=[], attachment=[]):

  self.from_addr = from_addr
  self.subject = subject

  if to_addr:
   if isinstance(to_addr, list):
    self.to_addr = to_addr
   else:
    self.to_addr = [d for d in to_addr.split(',')]
  else:
   self.to_addr = []

  if cc_addr:
   if isinstance(cc_addr, list):
    self.cc_addr = cc_addr
   else:
    self.cc_addr = [d for d in cc_addr.split(',')]
  else:
   self.cc_addr = []

  if html is not None:
   self.body = html
   self.body_type = "html"
  else:
   self.body = text
   self.body_type = "plain"

  self.parts = []
  if isinstance(attachment, list):
   for file in attachment:
    self.add_attachment(file)

 def add_attachment(self, file_path, mimetype=None):
  """
   If *mimetype* is not specified an attempt to guess it is made. If nothing
   is guessed then `application/octet-stream` is used.
  """
  if not mimetype:
   mimetype, _ = mimetypes.guess_type(file_path)

  if mimetype is None:
   mimetype = 'application/octet-stream'

  type_maj, type_min = mimetype.split('/')
  with open(file_path, 'rb') as fh:
   part_data = fh.read()

   part = MIMEBase(type_maj, type_min)
   part.set_payload(part_data)
   email_encoders.encode_base64(part)

   part_filename = os.path.basename(file_path)
   part.add_header('Content-Disposition', 'attachment; filename="%s"'
       % part_filename)
   part.add_header('Content-ID', part_filename)

   self.parts.append(part)

 def __to_mime_message(self):
  """Returns the message as
  :py:class:`email.mime.multipart.MIMEMultipart`."""

  ## To get the message work in iOS, you need use multipart/related, not the multipart/alternative
  msg = MIMEMultipart('related')
  msg['Subject'] = self.subject
  msg['From'] = self.from_addr
  msg['To'] = ','.join(self.to_addr)

  if len(self.cc_addr) > 0:
   msg['CC'] = ','.join(self.cc_addr)

  body = MIMEText(self.body, self.body_type)
  msg.attach(body)

  # Add Attachment
  for part in self.parts:
   msg.attach(part)

  return msg

 def send(self, smtp_server='localhost'):

  smtp = smtplib.SMTP()
  smtp.connect(smtp_server)
  smtp.sendmail(from_addr=self.from_addr, to_addrs=self.to_addr + self.cc_addr, msg=self.__to_mime_message().as_string())
  smtp.close()

對(duì)于實(shí)際發(fā)送程序,要注意個(gè)參數(shù)的類(lèi)型,比如from_addr是字符串,to_addr和cc_addr以及attachment都是列表

from mail_base import Message
import datetime
from_addr = 'xxx'
mail_to = 'xxx'


def send_go():
 time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
 attach_files = ['testcsv.xlsm','test1.jpg','test2.jpg','test3.jpg']
 mail_msg = """
  <p>Hi Lockey:</p>
  <p><img src="cid:test1.jpg"></p>####要特別注意這里,正文插入圖片的特殊格式?。?!
  <hr/>
  <p style="text-indent:16px">Here is the latest paper link from The Economist, you can click <a  rel="external nofollow" >Go</a> for a full view!</p>
  <hr/>
  <p>Best Regards</p>
  <p>
   Any question please mail to <a href='mailto:iooiooi23@163.com'>Lockey23</a>.
  </p>
  <p>Sent at {} PST</p>
  """.format(time_now)
 subject = '[Halo] - ' + 'A new paper published!'
 msg = Message(from_addr=from_addr,
     to_addr=[mail_to],
     cc_addr=[mail_to],
     subject=subject,
     attachment=attach_files,
     html=mail_msg
     )
 msg.send()

if __name__ == '__main__':
 send_go()

對(duì)于測(cè)試程序我們命名為sendGo.py,運(yùn)行測(cè)試程序

~$ python sendGo.py

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python利用不到一百行代碼實(shí)現(xiàn)一個(gè)小siri

    python利用不到一百行代碼實(shí)現(xiàn)一個(gè)小siri

    這篇文章主要介紹了關(guān)于python利用不到一百行代碼實(shí)現(xiàn)了一個(gè)小siri的相關(guān)資料,文中介紹的很詳細(xì),對(duì)大家具有一定的參考借鑒價(jià)值,需要的朋友們下面來(lái)一起看看吧。
    2017-03-03
  • windows10系統(tǒng)中安裝python3.x+scrapy教程

    windows10系統(tǒng)中安裝python3.x+scrapy教程

    本文給大家主要介紹了在windows10系統(tǒng)中安裝python3以及scrapy框架的教程以及有可能會(huì)遇到的問(wèn)題的解決辦法,希望大家能夠喜歡
    2016-11-11
  • TensorFlow實(shí)現(xiàn)Batch Normalization

    TensorFlow實(shí)現(xiàn)Batch Normalization

    這篇文章主要為大家詳細(xì)介紹了TensorFlow實(shí)現(xiàn)Batch Normalization,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • 淺談Python中用datetime包進(jìn)行對(duì)時(shí)間的一些操作

    淺談Python中用datetime包進(jìn)行對(duì)時(shí)間的一些操作

    下面小編就為大家?guī)?lái)一篇淺談Python中用datetime包進(jìn)行對(duì)時(shí)間的一些操作。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2016-06-06
  • Opencv-Python圖像透視變換cv2.warpPerspective的示例

    Opencv-Python圖像透視變換cv2.warpPerspective的示例

    今天小編就為大家分享一篇關(guān)于Opencv-Python圖像透視變換cv2.warpPerspective的示例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-04-04
  • Python數(shù)據(jù)挖掘中常用的五種AutoEDA 工具總結(jié)

    Python數(shù)據(jù)挖掘中常用的五種AutoEDA 工具總結(jié)

    大家好,我們都知道在數(shù)據(jù)挖掘的過(guò)程中,數(shù)據(jù)探索性分析一直是非常耗時(shí)的一個(gè)環(huán)節(jié),但也是繞不開(kāi)的一個(gè)環(huán)節(jié),本篇文章帶你盤(pán)點(diǎn)數(shù)據(jù)挖掘中常見(jiàn)的5種 AutoEDA 工具
    2021-11-11
  • Python實(shí)現(xiàn)簡(jiǎn)單的俄羅斯方塊游戲

    Python實(shí)現(xiàn)簡(jiǎn)單的俄羅斯方塊游戲

    這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)簡(jiǎn)單的俄羅斯方塊游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • 使用Python實(shí)現(xiàn)將PDF轉(zhuǎn)為PDF/A和PDF/X

    使用Python實(shí)現(xiàn)將PDF轉(zhuǎn)為PDF/A和PDF/X

    PDF/A和PDF/X是兩種有特定用途的PDF格式,本文主要介紹了如何使用Python將PDF轉(zhuǎn)換為PDF/A和PDF/X,以及如何將PDF/A格式轉(zhuǎn)換回標(biāo)準(zhǔn)的PDF格式,需要的可以參考下
    2024-04-04
  • 解決pytorch-gpu 安裝失敗的記錄

    解決pytorch-gpu 安裝失敗的記錄

    這篇文章主要介紹了解決pytorch-gpu 安裝失敗的記錄,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Pytest運(yùn)行及其控制臺(tái)輸出信息

    Pytest運(yùn)行及其控制臺(tái)輸出信息

    這篇文章主要介紹了Pytest運(yùn)行及其控制臺(tái)輸出信息,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-09-09

最新評(píng)論