溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python3實(shí)現(xiàn)帶多張圖片、附件的郵件發(fā)送

發(fā)布時(shí)間:2020-09-15 12:27:15 來源:腳本之家 閱讀:177 作者:SoaringXu 欄目:開發(fā)技術(shù)

本文實(shí)例為大家分享了python3實(shí)現(xiàn)多張圖片附件郵件發(fā)送的具體代碼,供大家參考,具體內(nèi)容如下

直接上代碼,沒有注釋!

from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.header import Header

class Mail(object):
  def __init__(self, host, nickname, username, password, postfix):
    self.host = host
    self.nickname = nickname
    self.username = username
    self.password = password
    self.postfix = postfix

  def send_mail(self, to_list, subject, content, cc_list=[], encode='gbk', is_html=True, images=[]):
    me = str(Header(self.nickname, encode)) + "<" + self.username + "@" + self.postfix + ">"
    msg = MIMEMultipart()
    msg['Subject'] = Header(subject, encode)
    msg['From'] = me
    msg['To'] = ','.join(to_list)
    msg['Cc'] = ','.join(cc_list)
    if is_html:
      mail_msg = ''
      for i in range(len(images)):
        mail_msg += '<p><img src="cid:image%d" height="240" width="320"></p>' % (i+1)
      msg.attach(MIMEText(content + mail_msg, 'html', 'utf-8'))

      for i, img_name in enumerate(images):
        with open(img_name, 'rb') as fp:
          img_data = fp.read()
        msg_image = MIMEImage(img_data)
        msg_image.add_header('Content-ID', '<image%d>' % (i+1))
        msg.attach(msg_image)
        # 將圖片作為附件
        # image = MIMEImage(img_data, _subtype='octet-stream')
        # image.add_header('Content-Disposition', 'attachment', filename=images[i])
        # msg.attach(image)
    else:
      msg_content = MIMEText(content, 'plain', encode)
      msg.attach(msg_content)

    try:
      s = smtplib.SMTP()
      # s.set_debuglevel(1)
      s.connect(self.host)
      s.login(self.username, self.password)
      s.sendmail(me, to_list + cc_list, msg.as_string())
      s.quit()
      s.close()
      return True
    except Exception as e:
      print(e)
      return False

def send_mail(to_list, title, content, cc_list=[], encode='utf-8', is_html=True, images=[]):
  content = '<pre>%s</pre>' % content
  m = Mail('smtp.163.com', 'TV-APP TEST', 'tvapp_qa', 'ujlnluutpfespgxz', '163.com')
  m.send_mail(to_list, title, content, cc_list, encode, is_html, images)


if __name__ == '__main__':
  images = [
    '1.png',
    '2.png',
    '3.png',
    '4.png',
  ]
  import time
  title = 'new images %s' % time.strftime('%H:%M:%S')
  content = 'this is attach images %s' % time.time()
  send_mail(['x@163.com'], title, content, ['xx@163.com', 'xxx@163.com'], 'utf-8', True, images)

后記

調(diào)試發(fā)送多張圖片的時(shí)候遇到的問題:

用for循環(huán)生成的mail_msg,不能直接attach,需要和content一起attach

mail_msg = ''
for i in range(len(images)):
  mail_msg += '<p><img src="cid:image%d" height="240" width="320"></p>' % (i+1)
  msg.attach(MIMEText(**content** + mail_msg, 'html', 'utf-8'))

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

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI