91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python2.7實現郵件發送功能

發布時間:2020-09-29 14:31:21 來源:腳本之家 閱讀:159 作者:Lockeyi 欄目:開發技術

要想實現一個能夠發送帶有文本、圖片、附件的python程序,首先要熟悉兩大模塊:

email以及smtplib

然后對于MIME(郵件擴展)要有一定認知,因為有了擴展才能發送附件以及圖片這些媒體或者非文本信息

最后一個比較細節的方法就是MIMEMultipart,要理解其用法以及對應參數所實現的功能區別

發送郵件三部曲:

創建協議對象
連接郵件服務器
登陸并發送郵件

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()

對于實際發送程序,要注意個參數的類型,比如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 >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()

對于測試程序我們命名為sendGo.py,運行測試程序

~$ python sendGo.py

python2.7實現郵件發送功能

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

兴海县| 东丰县| 马关县| 手机| 天津市| 新巴尔虎左旗| 灌阳县| 响水县| 丰台区| 岚皋县| 九江市| 鄂温| 正阳县| 商洛市| 泗洪县| 旺苍县| 深州市| 金沙县| 噶尔县| 巴彦淖尔市| 金川县| 沙田区| 商都县| 友谊县| 梅州市| 洱源县| 大英县| 攀枝花市| 凤冈县| 仪陇县| 内乡县| 商水县| 巴林左旗| 乡宁县| 乌兰县| 福州市| 蓝田县| 锡林浩特市| 历史| 宜宾市| 长治市|