python3实现带多张图片、附件的邮件发送

yipeiwu_com5年前Python基础

本文实例为大家分享了python3实现多张图片附件邮件发送的具体代码,供大家参考,具体内容如下

直接上代码,没有注释!

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)

后记

调试发送多张图片的时候遇到的问题:

用for循环生成的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'))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

微信跳一跳python辅助软件思路及图像识别源码解析

微信跳一跳python辅助软件思路及图像识别源码解析

本文将梳理github上最火的wechat_jump_game的实现思路,并解析其图像处理部分源码 首先废话少说先看效果 核心思想 获取棋子到下一个方块的中心点的距离 计算触摸屏...

机器学习python实战之手写数字识别

机器学习python实战之手写数字识别

看了上一篇内容之后,相信对K近邻算法有了一个清晰的认识,今天的内容——手写数字识别是对上一篇内容的延续,这里也是为了自己能更熟练的掌握k-NN算法。 我们有大约2000个训练样本和100...

机器学习之KNN算法原理及Python实现方法详解

本文实例讲述了机器学习之KNN算法原理及Python实现方法。分享给大家供大家参考,具体如下: 文中代码出自《机器学习实战》CH02,可参考本站: 机器学习实战 (Peter Harri...

python逆序打印各位数字的方法

如下所示: # -*- coding: utf-8 -*- # raw_input获取给定的一个不多于5位的正整数。 # 一、求它是几位数; # 二、逆序打印出各位数字。 def f...

python动态监控日志内容的示例

日志文件一般是按天产生,则通过在程序中判断文件的产生日期与当前时间,更换监控的日志文件程序只是简单的示例一下,监控test1.log 10秒,转向监控test2.log 程序监控使用是l...