sendEmail 工具类

package com.greenet.nsmas.desk.utils;


import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.protocol.IMAPProtocol;
import org.springframework.util.StringUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.SharedByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

import static com.greenet.nsmas.desk.utils.POP3Receive.parseMessage;


public class EmailUtil {

    public static void sendEmail(String username, String password, String recipient, String content, String subject, List<File> fileList, String emailServer){
        Properties prop = new Properties();
        prop.setProperty("mail.host", emailServer);// 需要修改
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");

        try {
            // 使用JavaMail发送邮件的5个步骤
            // 1、创建session
            Session session = Session.getInstance(prop);
            // 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
            session.setDebug(true);
            // 2、通过session得到transport对象
            Transport ts = session.getTransport();
            // 3、连上邮件服务器,需要发件人提供邮箱的用户名和密码进行验证
            ts.connect(emailServer, username, password);// 需要修改
            // 4、创建邮件
            Message message = createAttachMail(session,fileList,username,recipient,content,subject);
            // 5、发送邮件
            try {
                ts.sendMessage(message, message.getAllRecipients());
            } catch (MessagingException e) {
            }
            ts.close();
        }catch (Exception e){

        }

    }

    public static MimeMessage createAttachMail(Session session,List<File> fileList,String username,String recipient,String content,String subject){
        MimeMessage message = new MimeMessage(session);
        try {
            // 设置邮件的基本信息
            message.setFrom(new InternetAddress(username));    // 发件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));// 收件人
            // 邮件标题
            message.setSubject(subject);

            // 创建邮件正文,为了避免邮件正文中文乱码问题,需要使用charset=UTF-8指明字符编码
            MimeBodyPart text = new MimeBodyPart();
            text.setContent(content, "text/html;charset=UTF-8");

            // 创建容器描述数据关系
            MimeMultipart mp = new MimeMultipart();
            for(File f:fileList){
                // 创建邮件附件
                MimeBodyPart attach = new MimeBodyPart();
                DataHandler dh = new DataHandler(new FileDataSource(f));// 需要修改
                attach.setDataHandler(dh);
                attach.setFileName(dh.getName());
                mp.addBodyPart(attach);
            }

            mp.addBodyPart(text);
            mp.setSubType("mixed");
            message.setContent(mp);
            message.saveChanges();
            // 返回生成的邮件
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        return message;
    }
    public static String imapReceiveEmail(String username, String password, String emailIp, Boolean close) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", emailIp);
        prop.setProperty("mail.transport.protocol", "imap");
        prop.setProperty("mail.imap.port", "143");
        prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码
        prop.setProperty("mail.mime.multipart.allowempty", "true");
        prop.setProperty("mail.debug","false");
        //使用JavaMail发送邮件的5个步骤

        //创建定义整个应用程序所需的环境信息的 Session 对象

        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            Store store = session.getStore("imap");//指定接收邮件协议
            store.connect(emailIp, username, password);
            // 获得收件箱
            Folder folder = store.getFolder("INBOX");
            IMAPFolder imapFolder = (IMAPFolder) folder;
            imapFolder.doCommand(new IMAPFolder.ProtocolCommand() {
                public Object doCommand(IMAPProtocol p) {
                    try {
                        p.id("FUTONG");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            });
            //Folder.READ_ONLY:只读权限
            //Folder.READ_WRITE:可读可写(可以修改邮件的状态)
            imapFolder.open(Folder.READ_WRITE);    //打开收件箱

            // 得到收件箱中的所有邮件,并解析
            Message[] messages = folder.getMessages();

            if (messages == null || messages.length < 1) {
                store.close();
                return null;
            }

            // 解析所有邮件
            for (int i = 0, count = messages.length; i < count; i++) {
                // 从文件夹中获取消息对象
                // 通常的方式,例如:

                MimeMessage msg = (MimeMessage) messages[i];

                // 通过写入字节数组来复制消息
                // 根据内容创建一个新的 MimeMessage 对象
                // 字节数组:
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                msg.writeTo(bos);
                bos.close();
                SharedByteArrayInputStream  bis= new
                        SharedByteArrayInputStream(bos.toByteArray());
                MimeMessage cmsg = new MimeMessage(session, bis);
                msg.setFlag(Flags.Flag.DELETED, true); // set the DELETED flag
                parseMessage(cmsg);
                bis.close();
            }
            if (close) {
                imapFolder.close(true);
            }
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void parseEml(Message msg) throws Exception {
        // 发件人信息
        Address[] froms = msg.getFrom();
        if (froms != null) {
            // System.out.println("发件人信息:" + froms[0]);
            InternetAddress addr = (InternetAddress) froms[0];
            System.out.println("发件人地址:" + addr.getAddress());
            System.out.println("发件人显示名:" + addr.getPersonal());
        }
        System.out.println("邮件主题:" + msg.getSubject());
        // getContent() 是获取包裹内容, Part相当于外包装
        Object o = msg.getContent();
        if (o instanceof Multipart) {
            Multipart multipart = (Multipart) o;
            reMultipart(multipart);
        } else if (o instanceof Part) {
            Part part = (Part) o;
            rePart(part);
        } else {
            System.out.println("类型" + msg.getContentType());
            System.out.println("内容" + msg.getContent());
        }
    }


    /**
     * @param part
     *            解析内容
     * @throws Exception
     */
    private static void rePart(Part part) throws Exception {

        if (part.getDisposition() != null) {

            String strFileNmae = part.getFileName();
            if(!StringUtils.isEmpty(strFileNmae))
            {  // MimeUtility.decodeText解决附件名乱码问题
                strFileNmae=MimeUtility.decodeText(strFileNmae);
                System.out.println("发现附件: "+ strFileNmae);

                InputStream in = part.getInputStream();// 打开附件的输入流
                // 读取附件字节并存储到文件中
                java.io.FileOutputStream out = new FileOutputStream(strFileNmae);
                int data;
                while ((data = in.read()) != -1) {
                    out.write(data);
                }
                in.close();
                out.close();

            }

            System.out.println("内容类型: "+ MimeUtility.decodeText(part.getContentType()));
            System.out.println("附件内容:" + part.getContent());


        } else {
            if (part.getContentType().startsWith("text/plain")) {
                System.out.println("文本内容:" + part.getContent());
            } else {
                // System.out.println("HTML内容:" + part.getContent());
            }
        }
    }

    /**
     * @param multipart
     *            // 接卸包裹(含所有邮件内容(包裹+正文+附件))
     * @throws Exception
     */
    private static void reMultipart(Multipart multipart) throws Exception {
        // System.out.println("邮件共有" + multipart.getCount() + "部分组成");
        // 依次处理各个部分
        for (int j = 0, n = multipart.getCount(); j < n; j++) {
            // System.out.println("处理第" + j + "部分");
            Part part = multipart.getBodyPart(j);// 解包, 取出 MultiPart的各个部分,
            // 每部分可能是邮件内容,
            // 也可能是另一个小包裹(MultipPart)
            // 判断此包裹内容是不是一个小包裹, 一般这一部分是 正文 Content-Type: multipart/alternative
            if (part.getContent() instanceof Multipart) {
                Multipart p = (Multipart) part.getContent();// 转成小包裹
                // 递归迭代
                reMultipart(p);
            } else {
                rePart(part);
            }
        }
    }



    public static String pop3ReceiveEmail(String username, String password, String emailIp, Boolean close) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", username);
        prop.put("mail.store.protocol", "pop3");
        prop.setProperty("mail.smtp.auth", "false"); // 需要验证用户名密码

        //使用JavaMail发送邮件的5个步骤

        //创建定义整个应用程序所需的环境信息的 Session 对象

        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            Store store = session.getStore("pop3");//指定接收邮件协议
            store.connect(emailIp, username, password);
            // 获得收件箱
            Folder folder = store.getFolder("INBOX");
            //Folder.READ_ONLY:只读权限
            //Folder.READ_WRITE:可读可写(可以修改邮件的状态)
            folder.open(Folder.READ_WRITE);    //打开收件箱

            // 获得收件箱中的邮件总数
            System.out.println("邮件总数: " + folder.getMessageCount());

            // 得到收件箱中的所有邮件,并解析
            Message[] messages = folder.getMessages();

            if (messages == null || messages.length < 1) {
                store.close();
                return null;
            }

            // 解析所有邮件
            for (int i = 0, count = messages.length; i < count; i++) {
                MimeMessage msg = (MimeMessage) messages[i];
                //System.out.println("----------第"+i+"份---------");
                msg.setFlag(Flags.Flag.DELETED, true); // set the DELETED flag
                parseMessage(msg);
                //Receive receive = new Receive(msg.getMessageNumber(), getFrom(msg), getSubject(msg), getSentDate(msg, null));
            }
            if (close) {
                folder.close(true);
            }
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

本地抓包 服务器抓包数据一样
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值