码迷,mamicode.com
首页 > 编程语言 > 详细

python发送smtp 邮件 图片

时间:2016-02-23 00:52:03      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

#-*- 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(umeizi.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)

 

python发送smtp 邮件 图片

标签:

原文地址:http://www.cnblogs.com/duanguyuan/p/5208590.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!