邮箱发送,带附件、图片

邮箱发送,带附件,图片`

一、代码实现

package org.jeecg.modules.sendEmail.job;

import com.alibaba.excel.metadata.Sheet;
import com.sun.mail.util.MailSSLSocketFactory;
import com.sun.prism.Image;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Response;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.sendEmail.entity.Aging;
import org.jeecg.modules.sendEmail.entity.Boh;
import org.jeecg.modules.sendEmail.mapper.AgingMapper;
import org.jeecg.modules.utils.ExcelExportUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.annotation.Resource;
import javax.imageio.stream.FileImageOutputStream;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Slf4j
@Component
public class SendMailService {
    @Resource
    private AgingMapper agingMapper;

    @XxlJob(value = "sendEmailAging")
    public ReturnT<String> sendEmailAging(String param){
        //将网页转成图片
        String s = webPageToPicture("http://13.13.32.25:8091/pubhtmltoimg/?url=http://11.11.211.215:8080/webroot/decision/view/report?viewlet=.cpt&imgname=AGING","");
        //图片文件存放地址
        String imagePath = "D:/AGING/AGING.png";
        getPicture("http://113.13.32.25:8091/pubFile/?filename=AGING.png","",imagePath);
        toAgingExcel();
        //设置发信的图片文件和附件
        String fileName = "D:/AGING/AGING.xlsx";
        String fileNameReal = "AGING.xlsx";
        String imgName = "D:/AGING/AGING.png";
        sendEmailWithPictureAndFileAging(fileName,fileNameReal,imgName);
        return ReturnT.SUCCESS;
    }
    @XxlJob(value = "sendEmailBoh")
    public ReturnT<String> sendEmailBoh(String param){
        //将网页转成图片
        String s = webPageToPicture("http://13.13.32.25:8091/pubhtmltoimg/?url=http://13.13.32.25:8091/webroot/decision/view/report?viewlet=U09/U09/BOH_NEW_TEST.cpt&imgname=BOH","");
        //图片文件存放地址
        String imagePath = "D:/BOH/BOH.png";
        getPicture("http://13.13.32.25:8091/pubFile/?filename=BOH.png","",imagePath);
        toBohExcel();
        //设置发信的图片文件和附件
        String fileName = "D:/BOH/BOH.xlsx";
        String fileNameReal = "BOH.xlsx";
        String imgName = "D:/BOH/BOH.png";
        sendEmailWithPictureAndFileBoh(fileName,fileNameReal,imgName);
        return ReturnT.SUCCESS;
    }
    @XxlJob(value = "sendDailyIoReport")
    public ReturnT<String> DailyIoReport(String param){
        //将网页转成图片
        String s = webPageToPicture("http://13.13.32.25:8091/pubhtmltoimg/?url=http://10.10.10.215:8080/webroot/decision/view/report?viewlet=U09/U09/Customer/customer_mail.cpt&imgname=report","");
        //图片文件存放地址
        String imagePath = "D:/REPORT/report.png";
        getPicture("http://13.13.32.25:8091/pubFile/?filename=report.png","",imagePath);
        toAgingExcel();
        //设置发信的图片文件和附件
        String imgName = "D:/REPORT/report.png";
        sendEmailDailyIoReport(imgName);
        return ReturnT.SUCCESS;
    }
    /**
     * 调用对方接口方法,将网页转换成图片
     * @param path 对方或第三方提供的路径
     * @param data 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析
     */
    public static String webPageToPicture(String path,String data) {
        String str = "";
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;

            /**设置URLConnection的参数和普通的请求属性****start***/

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            /**设置URLConnection的参数和普通的请求属性****end***/

            //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
            //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod("GET");//GET和POST必须全大写
            /**GET方法请求*****start*/
            /**
             * 如果只是发送GET方式请求,使用connet方法建立和远程资源之间的实际连接即可;
             * 如果发送POST方式的请求,需要获取URLConnection实例对应的输出流来发送请求参数。
             * */
            conn.connect();

            /**GET方法请求*****end*/

            /***POST方法请求****start*/

            /*out = new PrintWriter(conn.getOutputStream());//获取URLConnection对象对应的输出流

            out.print(data);//发送请求参数即数据

            out.flush();//缓冲数据
            */
            /***POST方法请求****end*/

            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
//            ByteArrayOutputStream output = new ByteArrayOutputStream();
//            byte[] buffer = new byte[1024*4];
//            int n = 0;
//            while (-1 != (n = is.read(buffer))) {
//                output.write(buffer, 0, n);
//            }
//            byte[] bytes = output.toByteArray();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String s = "";
            while ((s = br.readLine()) != null) {
                str=new String(s.getBytes(),"UTF-8");//解决中文乱码问题
            }
            //关闭流
            is.close();
            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
    /**
     * 再次调用相关接口,将图片存到服务端指定位置
     * @param path
     * @param data
     * @param imagePath
     */
    public static void getPicture(String path,String data,String imagePath) {

        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;

            /**设置URLConnection的参数和普通的请求属性****start***/

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            /**设置URLConnection的参数和普通的请求属性****end***/

            //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
            //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod("GET");//GET和POST必须全大写
            /**GET方法请求*****start*/
            /**
             * 如果只是发送GET方式请求,使用connet方法建立和远程资源之间的实际连接即可;
             * 如果发送POST方式的请求,需要获取URLConnection实例对应的输出流来发送请求参数。
             * */
            conn.connect();

            /**GET方法请求*****end*/

            /***POST方法请求****start*/

            /*out = new PrintWriter(conn.getOutputStream());//获取URLConnection对象对应的输出流

            out.print(data);//发送请求参数即数据

            out.flush();//缓冲数据
            */
            /***POST方法请求****end*/

            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024*4];
            int n = 0;
            while (-1 != (n = is.read(buffer))) {
                output.write(buffer, 0, n);
            }
            byte[] bytes = output.toByteArray();
            File file = new File(imagePath);
            //如果已经存在则删除
            if (file.exists()) {
                file.delete();
            }
            //检查父包是否存在
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            //创建文件
            file.createNewFile();
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(imagePath));
            imageOutput.write(bytes, 0, bytes.length);
            imageOutput.close();
            System.out.println("Make Picture success,Please find image in " + imagePath);

            //关闭流
            is.close();
            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 将excel文件存到服务端指定位置
     * @param
     */
    public void toAgingExcel(){
        try {

            String path = "D:/AGING/AGING.xlsx";
            File file = new File(path);
            //如果已经存在则删除
            if (file.exists()) {
                file.delete();
            }
            //检查父包是否存在
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            //创建文件
            file.createNewFile();
            Map columnWidth = new HashMap();
            columnWidth.put(0, 8000);

            String fileName = "AGING";
            List<Aging> Aging = agingMapper.agingExportXlsx();
            Sheet sheet1 = new Sheet(1, 0, Aging.class);
            sheet1.setColumnWidthMap(columnWidth);
            sheet1.setSheetName(fileName);
            ExcelExportUtils.writeExcelOneSheet3(Aging,sheet1,fileName,path);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public void toBohExcel(){
        try {

            String path = "D:/BOH/BOH.xlsx";
            File file = new File(path);
            //如果已经存在则删除
            if (file.exists()) {
                file.delete();
            }
            //检查父包是否存在
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            //创建文件
            file.createNewFile();

            Map columnWidth = new HashMap();
            columnWidth.put(0, 8000);

            String fileName = "BOH";
            List<Boh> boh = agingMapper.bohExportXlsx();
            Sheet sheet1 = new Sheet(1, 0, Boh.class);
            sheet1.setColumnWidthMap(columnWidth);
            sheet1.setSheetName(fileName);
            ExcelExportUtils.writeExcelOneSheet3(boh,sheet1,fileName,path);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送邮件(文字+图片+附件)
     * @param fileName
     * @param fileNameReal
     * @param imgName
     */
    public void sendEmailWithPictureAndFileAging(String fileName,String fileNameReal,String imgName) {
        // 收件人电子邮箱
        //String to = "krystal.cao@goertek.com";
        //String to = "zhuang.qiao@goertek.com";

        // 发件人电子邮箱
        String from = "u09noreply.sys@goertek.com";
        // 指定发送邮件的主机为 goertek.com
        String host = "smtp.goertek.com";  //goertek 邮件服务器
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {     //qq邮箱服务器账户、第三方登录授权码
                return new PasswordAuthentication("u09noreply.sys@goertek.com", "Hddb8442"); //发件人邮件用户名、密码
            }
        });
        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));
            // Set To: 头部头字段
            //设置收件人电子邮箱
            Address[] addresses = new Address[10];
            addresses[0] = new InternetAddress("aileen.gai@goertek.com"); //设置收件人1
            addresses[1] = new InternetAddress("cindy.wang@goertek.com"); //设置收件人2
            addresses[2] = new InternetAddress("alan.zhaoyh@goertek.com"); //设置收件人2
            addresses[3] = new InternetAddress("terry.wangs@goertek.com"); //设置收件人2
            addresses[4] = new InternetAddress("owen.liuz@goertek.com"); //设置收件人2
            addresses[5] = new InternetAddress("ebony.liu@goertek.com"); //设置收件人2
            addresses[6] = new InternetAddress("zhijun.ding@goertek.com"); //设置收件人2
            addresses[7] = new InternetAddress("dick.du@goertek.com"); //设置收件人2
            addresses[8] = new InternetAddress("apple.jian@goertek.com"); //设置收件人2
            addresses[9] = new InternetAddress("devin.jii@goertek.com"); //设置收件人2
            //message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));单个收件人
            message.addRecipients(Message.RecipientType.TO,addresses);
            // Set Subject: 主题文字
            message.setSubject("Hollywood/Seacliff-Aging Kanban");
            // 创建消息部分
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            // 消息
            //messageBodyPart.setText("这是一条内容有图片,附件是excel的邮件");
            //设置发送的图片
            //创建图片节点
            MimeBodyPart img = new MimeBodyPart();
            //读取本地图片文件
            DataHandler dh = new DataHandler(new FileDataSource(new File(imgName)));
            //将图片数据添加到节点
            img.setDataHandler(dh);
            //为节点设置一个唯一编号(在文本节点将引用该编号)
            img.setContentID("mailTestPic");
            messageBodyPart.setContent("Dear Team:<br/>Below is Hollywood/Seacliff-Aging Kanban information, please kindly review, thanks.<br/>This email is automatically sent through system, please don't reply this email.<br/><img src='cid:mailTestPic'/></a>", "text/html;charset=UTF-8");

            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart); //文本
            multipart.addBodyPart(img);  //图片


            // 附件部分
            messageBodyPart = new MimeBodyPart();
            //设置要发送附件的文件路径
            try {
                DataSource source = new FileDataSource(fileName);
                messageBodyPart.setDataHandler(new DataHandler(source));
                //messageBodyPart.setFileName(filename);
                //处理附件名称中文(附带文件路径)乱码问题
                try {
                    messageBodyPart.setFileName(MimeUtility.encodeText(fileNameReal));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                multipart.addBodyPart(messageBodyPart);//如果有多个附件,可以创建多个多次添加
                // 发送完整消息
                message.setContent(multipart);
                //   发送消息
                Transport.send(message);
                System.out.println("Sent message successfully....");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
    public void sendEmailWithPictureAndFileBoh(String fileName,String fileNameReal,String imgName) {
        // 收件人电子邮箱
        //String to = "krystal.cao@goertek.com";
        //String to = "zhuang.qiao@goertek.com";

        // 发件人电子邮箱
        String from = "unoreply.sys@.com";
        // 指定发送邮件的主机为 goertek.com
        String host = "smtp.goertek.com";  //goertek 邮件服务器
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {     //qq邮箱服务器账户、第三方登录授权码
                return new PasswordAuthentication("u09noreply.sys@goertek.com", "Hddb8442"); //发件人邮件用户名、密码
            }
        });
        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));
            // Set To: 头部头字段
            //设置收件人电子邮箱
            Address[] addresses = new Address[10];
            addresses[0] = new InternetAddress("aileen.gai@.com"); //设置收件人1
            addresses[1] = new InternetAddress("cindy.wang@.com"); //设置收件人2
            addresses[2] = new InternetAddress("alan.zhaoyh@.com"); //设置收件人2
            addresses[3] = new InternetAddress("terry.wangs@.com"); //设置收件人2
            addresses[4] = new InternetAddress("owen.liuz@.com"); //设置收件人2
            addresses[5] = new InternetAddress("ebony.liu@com"); //设置收件人2
            addresses[6] = new InternetAddress("zhijun.ding@.com"); //设置收件人2
            addresses[7] = new InternetAddress("dick.du@.com"); //设置收件人2
            addresses[8] = new InternetAddress("apple.jian@.com"); //设置收件人2
            addresses[9] = new InternetAddress("devin.jii@.com"); //设置收件人2
            //message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));单个收件人
            message.addRecipients(Message.RecipientType.TO,addresses);
            // Set Subject: 主题文字
            message.setSubject("Hollywood/Seacliff-BOH Kanban");
            // 创建消息部分
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            // 消息
            //messageBodyPart.setText("这是一条内容有图片,附件是excel的邮件");
            //设置发送的图片
            //创建图片节点
            MimeBodyPart img = new MimeBodyPart();
            //读取本地图片文件
            DataHandler dh = new DataHandler(new FileDataSource(new File(imgName)));
            //将图片数据添加到节点
            img.setDataHandler(dh);
            //为节点设置一个唯一编号(在文本节点将引用该编号)
            img.setContentID("mailTestPic");
            messageBodyPart.setContent("Dear Team:<br/>Below is Hollywood/Seacliff-BOH Kanban information, please kindly review, thanks.<br/>This email is automatically sent through system, please don't reply this email.<br/><img src='cid:mailTestPic'/></a>", "text/html;charset=UTF-8");

            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart); //文本
            multipart.addBodyPart(img);  //图片


            // 附件部分
            messageBodyPart = new MimeBodyPart();
            //设置要发送附件的文件路径
            try {
                DataSource source = new FileDataSource(fileName);
                messageBodyPart.setDataHandler(new DataHandler(source));
                //messageBodyPart.setFileName(filename);
                //处理附件名称中文(附带文件路径)乱码问题
                try {
                    messageBodyPart.setFileName(MimeUtility.encodeText(fileNameReal));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                multipart.addBodyPart(messageBodyPart);//如果有多个附件,可以创建多个多次添加
                // 发送完整消息
                message.setContent(multipart);
                //   发送消息
                Transport.send(message);
                System.out.println("Sent message successfully....");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
    public void sendEmailDailyIoReport(String imgName) {
        // 收件人电子邮箱
        //String to = "krystal.cao@goertek.com";
        //String to = "zhuang.qiao@goertek.com";

        // 发件人电子邮箱
        String from = "u09noreply.sys@goertek.com";
        // 指定发送邮件的主机为 goertek.com
        String host = "smtp.goertek.com";  //goertek 邮件服务器
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {     //qq邮箱服务器账户、第三方登录授权码
                return new PasswordAuthentication("u9noreply.sys@.com", "XXXXXXX"); //发件人邮件用户名、密码
            }
        });
        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));
            // Set To: 头部头字段
            //设置收件人电子邮箱
            Address[] addresses = new Address[2];
            addresses[0] = new InternetAddress("devin.jii@goertek.com");
            addresses[1] = new InternetAddress("zhuang.qiao@goertek.com");
//            addresses[0] = new InternetAddress("aileen.gai@goertek.com"); //设置收件人1
//            addresses[1] = new InternetAddress("cindy.wang@goertek.com"); //设置收件人2
//            addresses[2] = new InternetAddress("alan.zhaoyh@goertek.com"); //设置收件人2
//            addresses[3] = new InternetAddress("terry.wangs@goertek.com"); //设置收件人2
//            addresses[4] = new InternetAddress("owen.liuz@goertek.com"); //设置收件人2
//            addresses[5] = new InternetAddress("ebony.liu@goertek.com"); //设置收件人2
//            addresses[6] = new InternetAddress("zhijun.ding@goertek.com"); //设置收件人2
//            addresses[7] = new InternetAddress("dick.du@goertek.com"); //设置收件人2
//            addresses[8] = new InternetAddress("apple.jian@goertek.com"); //设置收件人2
//            addresses[9] = new InternetAddress("devin.jii@goertek.com"); //设置收件人2
            //message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));单个收件人
            message.addRecipients(Message.RecipientType.TO,addresses);
            // Set Subject: 主题文字
            message.setSubject("Hollywood/Seacliff-Aging Kanban");
            // 创建消息部分
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            // 消息
            //messageBodyPart.setText("这是一条内容有图片,附件是excel的邮件");
            //设置发送的图片
            //创建图片节点
            MimeBodyPart img = new MimeBodyPart();
            //读取本地图片文件
            DataHandler dh = new DataHandler(new FileDataSource(new File(imgName)));
            //将图片数据添加到节点
            img.setDataHandler(dh);
            //为节点设置一个唯一编号(在文本节点将引用该编号)
            img.setContentID("mailTestPic");
            messageBodyPart.setContent("Dear Team:<br/>Below is Hollywood/Seacliff-Aging Kanban information, please kindly review, thanks.<br/>This email is automatically sent through system, please don't reply this email.<br/><img src='cid:mailTestPic'/></a>", "text/html;charset=UTF-8");

            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart); //文本
            multipart.addBodyPart(img);  //图片


            // 附件部分
//            messageBodyPart = new MimeBodyPart();
            //设置要发送附件的文件路径
            try {
//                DataSource source = new FileDataSource(fileName);
//                messageBodyPart.setDataHandler(new DataHandler(source));
//                //messageBodyPart.setFileName(filename);
//                //处理附件名称中文(附带文件路径)乱码问题
//                try {
//                    messageBodyPart.setFileName(MimeUtility.encodeText(fileNameReal));
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//                multipart.addBodyPart(messageBodyPart);//如果有多个附件,可以创建多个多次添加
                // 发送完整消息
                message.setContent(multipart);
                //   发送消息
                Transport.send(message);
                System.out.println("Sent message successfully....");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值