python发送html邮件(带图片)

#!/usr/bin/env python3
# coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import os
 
'''
发送多张图片邮件的python代码
'''
img_list = '图片所在的文件夹'
allfile=[]
 
'''
遍历文件夹获得所有图片绝对路径
'''
def getallfile(path):
    allfilelist=os.listdir(path)
    for file in allfilelist:
        filepath=os.path.join(path,file)
        if os.path.isdir(filepath):
            getallfile(filepath)
        else:
            allfile.append(filepath)
    return allfile
 
 
def sendmail(filelist):
    sender = 'aaa@.ddd.com'
    receiver = 'bbb@.eee.com'
    subject = 'python email with pictures'
    smtpserver = 'smtp.sina.com.cn'
 
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'= 'python email'
    '''
    图片id加入所在位置 
    '''
    content = '<b>Some <i>HTML</i> text</b> and an image.<br>'
    for index in range(len(filelist)):
        if index % 2 == 0:
            content += '<img src="cid:'+str(index)+'"><br>'
        else:
            content += '<img src="cid:' + str(index) + '">'
 
    msgText = MIMEText(content, 'html''utf-8')
    msgRoot.attach(msgText)
     
    '''
    将图片和id位置对应起来
    '''
    index = 0
    for file in filelist:
        fp = open(file'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header('Content-ID''<'+str(index)+'>')
        index += 1
        msgRoot.attach(msgImage)
 
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)
    smtp.sendmail(sender, receiver, msgRoot.as_string())
    smtp.quit()
 
 
if __name__ == '__main__':
    sendmail(getallfile(img_list))

 

java版本:

 

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.*;
import java.util.Map.Entry;
 
/**
 *
 * @author zongrun.yang
 *
 */
public class SendMail {
    private static final Properties prop = new Properties();
    // 发送邮件的服务器
    private static final String host = "";
 
    static {
        prop.put("mail.smtp.host", host);
    }
 
 
    static List<String> picture_list = new ArrayList<String>();
 
    public static List<String> getFileList(String strPath){
        File f=new File(strPath);
        try {
            if(f.isDirectory()){
                File[] fs=f.listFiles();
                for(int i=0;i<fs.length;i++){
                    String fsPath=fs[i].getAbsolutePath();
                    getFileList(fsPath);
                }
            }else if(f.isFile()){
                String fname=f.getAbsolutePath();
                //System.out.println(fname);
                picture_list.add(fname);
            }else{
                System.out.println("路径不正确!");
            }
        }catch (Exception e) {
            System.out.println("遍历异常");
        }
        return picture_list;
    }
 
    public static void main(String[] args) throws Exception {
        String path = "path";
        String from = "data@d.com";
        String subject = "日报";
        String content="<p>日报</p><br/>";
        String to = "aaaa@ccc.com";
        String cc = "bbbb@dddd.com";
        sendPictureMail(from,subject,content,cc,to,path);
    }
 
    public static void sendPictureMail(String fromAddress,String subject,String content,String receivers,String cc,String path) throws Exception {
 
        Map<String, String> image = new HashMap<String, String>();
 
        List<String> fileList = SendMailcopy.getFileList(path);
        System.out.println(fileList.size());
        for (int i = 0; i < fileList.size(); i++) {
            image.put(i + "", fileList.get(i));
            if (i % 2 == 0) {
                content += "<img src=\"cid:" + i + "\"><br/><br/>";
            else {
                content += "<img src=\"cid:" + i + "\">";
            }
        }
        Session session = Session.getInstance(prop);
 
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
 
        String[] toAddrs = receivers.split(";");
        if (toAddrs.length > 0) {
            Address[] addressList = new Address[toAddrs.length];
            int index = 0;
            for (String toAddr : toAddrs) {
                //if (StringUtils.isNotBlank(toAddr)) {
                    addressList[index++] = new InternetAddress(toAddr);
                //}
            }
            String[] ccAddrs = cc.split(";");
            Address[] ccList = new Address[ccAddrs.length];
            int index2 = 0;
            for (String ccAddr : ccAddrs) {
                //if (StringUtils.isNotEmpty(ccAddr)) {
                    ccList[index2++] = new InternetAddress(ccAddr);
                //}
            }
            message.setRecipients(Message.RecipientType.CC, ccList);
 
            message.setRecipients(Message.RecipientType.TO, addressList);
            message.setSubject(subject);
 
            MimeMultipart allMultipart = new MimeMultipart();
 
            MimeBodyPart contentPart = new MimeBodyPart();
            MimeMultipart contentMultipart = new MimeMultipart("related");
 
            MimeBodyPart htmlbodypart = new MimeBodyPart();
            htmlbodypart.setContent(content, "text/html;charset=UTF-8");
            contentMultipart.addBodyPart(htmlbodypart);
 
            if (image != null && image.size() > 0) {
                Set<Entry<String, String>> set = image.entrySet();
                for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
                    Entry<String, String> entry = (Entry<String, String>) iterator.next();
 
                    //创建用于保存图片的MimeBodyPart对象,并将它保存到MimeMultipart中
                    MimeBodyPart gifBodyPart = new MimeBodyPart();
                    //图片所在的目录的绝对路径
                    FileDataSource fds = new FileDataSource(entry.getValue());
 
                    gifBodyPart.setDataHandler(new DataHandler(fds));
                    //cid的值
                    gifBodyPart.setContentID(entry.getKey());
                    contentMultipart.addBodyPart(gifBodyPart);
                }
            }
            contentPart.setContent(contentMultipart);
            allMultipart.addBodyPart(contentPart);
            message.setContent(allMultipart);
            message.saveChanges();
            Transport.send(message);
        }
    }
 
}

 

posted on 2018-05-31 10:23  yangzrun  阅读(5815)  评论(0编辑  收藏  举报