python发送smtp 邮件 图片

#-*- coding: utf-8 -*-
# python2 
import os
import time
import random
import smtplib
from time import strftime
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase



img_list = os.listdir('/home/wy/Desktop/xx')
# img_list = os.listdir('/home/whucs/wangyong/xx')

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((\
        Header(name, 'utf-8').encode(), \
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))

def SendSSLEmail(to_list):
    # from_addr = "2543128906@qq.com"        #发件人
    # pwd = "tvsbkyufaeyceaeb"                     #密码
    # to_addr = "@qq.com"          #收件人
    # smtp_server = "smtp.qq.com"

    from_addr = "xxxxxx@126.com"        #发件人
    pwd = "xxxxxxxxx"                     #密码
    # # to_addr = "@qq.com"         #收件人
    smtp_server = "smtp.126.com"

    msg = MIMEMultipart()
    msg['From'] = _format_addr(u'meizi.jiandan <%s>' % from_addr)
    # msg['To'] = _format_addr(u'doggy <%s>' % to_addr)
    msg['To'] = ";".join(to_list)
    title = time.strftime("%Y-%m-%d",time.localtime()) + ' 煎蛋妹子图'
    msg['Subject'] = Header(title, 'utf-8').encode()

    # msg.attach(MIMEText('手机常年静音,接电话全靠缘分', 'html', 'utf-8'))


    for i in range(10):
        # 添加附件就是加上一个MIMEBase,从本地读取一个图片:
        img = random.choice(img_list)
        with open('xx/'+img, 'rb') as f:
            # 设置附件的MIME和文件名,这里是png类型:
            mime = MIMEBase('image', 'jpg', filename=img)
            # 加上必要的头信息:
            mime.add_header('Content-Disposition', 'attachment', filename=img)
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            # 把附件的内容读进来:
            mime.set_payload(f.read())
            # 用Base64编码:
            encoders.encode_base64(mime)
            # 添加到MIMEMultipart:
            msg.attach(mime)
            # msg.attach(MIMEText('<html><body><h1>Hello</h1><p><img src="cid:' + str(i) + '"></p></body></html>', 'html', 'utf-8'))
    
    server = smtplib.SMTP_SSL(smtp_server, 465)
    server.set_debuglevel(1)
    server.login(from_addr, pwd)
    server.sendmail(from_addr, to_list, msg.as_string()) # 一次可以发多人,list
    server.quit()



if __name__ == '__main__':
    mailto_list = ["490311@qq.com"]
    # mailto_list = ["5645297@qq.com","490171@qq.com","4257399@qq.com","11356346@qq.com"]

    SendSSLEmail(mailto_list)

 

转载于:https://www.cnblogs.com/duanguyuan/p/5208590.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值