欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

邮件发送与接收,支持163邮箱、outlook邮箱、exchange邮箱

程序员文章站 2022-06-28 20:17:28
邮件发送与接收,支持163邮箱、outlook邮箱、exchange邮箱依赖的jar包邮件收发公共服务层实现package com.example.demo.service.impl;import com.example.demo.model.EmailMessageBO;import com.example.demo.model.EmailSendBO;import com.example.demo.model.FileBean;import com.example.demo.serv...

邮件发送与接收,支持163邮箱、outlook邮箱、exchange邮箱

依赖的jar包

邮件发送与接收,支持163邮箱、outlook邮箱、exchange邮箱
邮件发送与接收,支持163邮箱、outlook邮箱、exchange邮箱

邮件收发公共服务层实现
package com.example.demo.service.impl;

import com.example.demo.model.EmailMessageBO;
import com.example.demo.model.EmailSendBO;
import com.example.demo.model.FileBean;
import com.example.demo.service.EmailCommonService;
import lombok.extern.slf4j.Slf4j;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.PropertySet;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
import microsoft.exchange.webservices.data.core.enumeration.search.LogicalOperator;
import microsoft.exchange.webservices.data.core.enumeration.search.SortDirection;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.core.service.item.Item;
import microsoft.exchange.webservices.data.core.service.schema.EmailMessageSchema;
import microsoft.exchange.webservices.data.core.service.schema.ItemSchema;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.Attachment;
import microsoft.exchange.webservices.data.property.complex.FileAttachment;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import microsoft.exchange.webservices.data.search.FindItemsResults;
import microsoft.exchange.webservices.data.search.ItemView;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.AndTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SentDateTerm;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @className: EmailCommonServiceImpl
 * @description: 邮件公共服务层
 * @author: wangzb01
 * @version: V1.0
 * @since: V1.0
 * @className: 2020-12-18 8:56
 */
@Slf4j
@Service
public class EmailCommonServiceImpl implements EmailCommonService {

    /**
     * @param user      邮箱地址
     * @param password  邮箱密码
     * @param emailType 邮箱类型
     * @return void
     * @description 发邮件-适用163邮箱、outlook邮箱、exchange邮箱
     * @author wangzb01
     * @date 2020-12-16 15:19
     */
    @Override
    public List<EmailMessageBO> receive(String user, String password, String emailType) {
        try {
            if ("163".equals(emailType)) {
                return receiveEmail163(user, password);
            } else if ("outlook".equals(emailType)) {
                return receiveEmailOutlook(user, password);
            } else if ("exchange".equals(emailType)) {
                return receiveEmailExchange(user, password);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("邮件接收异常。。。");
            return null;
        }
    }

    @Override
    public void send(EmailSendBO emailSendBO) {
        if ("163".equals(emailSendBO.getEmailType())) {
            this.sendEmail163(emailSendBO);
        } else if ("outlook".equals(emailSendBO.getEmailType())) {
            this.sendEmailOutlook(emailSendBO);
        } else if ("exchange".equals(emailSendBO.getEmailType())) {
            this.sendEmailExchange(emailSendBO);
        }
    }

    /**
     * @param user
     * @param password
     * @return java.util.List<com.kbao.kbcassist.common.bean.EmailInfoBean>
     * @description 163邮箱收件箱
     * @author wangzb01
     * @date 2020-12-16 15:14
     */
    private List<EmailMessageBO> receiveEmail163(String user, String password) throws Exception {
        // 准备连接服务器的会话信息
        Properties props = System.getProperties();
        String protocol = "pop3s";
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.pop3s.host", "pop.163.com");
        props.setProperty("mail.pop3s.port", "995");
        props.setProperty("mail.pop3s.auth", "true");
        props.setProperty("mail.pop3s.ssl.trust", "*");
        props.setProperty("mail.pop3s.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        // 创建Session实例对象
        Session session = Session.getInstance(props);
        Store store = session.getStore(protocol);
        // 163邮箱程序登录属于第三方登录所以这里的密码是163给的授权密码而并非普通的登录密码
        store.connect(user, password);
        // 获得收件箱
        Folder inbox = store.getFolder("INBOX");
        // Folder.READ_ONLY:只读权限;Folder.READ_WRITE:可读可写(可以修改邮件的状态)
        inbox.open(Folder.READ_ONLY);

        // 搜索当天的邮件,得到收件箱中的所有邮件,并解析
        SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, this.getDayStart());
        SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, this.getDayEnd());
        SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, comparisonTermLe);
        Message[] messages = inbox.search(comparisonAndTerm);
        // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
        log.debug("未读邮件数: " + inbox.getUnreadMessageCount());
        // 获得收件箱中的邮件总数
        log.debug("邮件总数: " + inbox.getMessageCount());
        // 解析邮件消息体
        List<EmailMessageBO> emailMessageBOList = parseMessage(messages);

        //得到收件箱中的所有邮件并且删除邮件
//        deleteMessage(messages);
        //释放资源
        inbox.close(true);
        store.close();
        return emailMessageBOList;
    }

    /**
     * @param
     * @return java.util.Date
     * @description 获取当天开始时间
     * @author wangzb01
     * @date 2020-12-23 10:33
     */
    private Date getDayStart() {
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DAY_OF_MONTH, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date dayStart = calendar.getTime();
        return dayStart;
    }

    /**
     * @param
     * @return java.util.Date
     * @description 获取当天结束时间
     * @author wangzb01
     * @date 2020-12-23 10:33
     */
    private Date getDayEnd() {
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DAY_OF_MONTH, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date dayEnd = calendar.getTime();
        return dayEnd;
    }

    /**
     * @param user
     * @param password
     * @return java.util.List<com.kbao.kbcassist.common.bean.EmailInfoBean>
     * @description outlook邮箱收件箱
     * @author wangzb01
     * @date 2020-12-16 15:18
     */
    private List<EmailMessageBO> receiveEmailOutlook(String user, String password) throws Exception {
        // 准备连接服务器的会话信息
        Properties props = System.getProperties();
        String protocol = "imap";
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        //如果我们希望JavaMail只处理SSL的连接, 对于非SSL的连接不做处理, 那么我们最好设置fallback为false
        props.setProperty("mail.imap.socketFactory.fallback", "false");
        props.setProperty("mail.imap.port", "993");
        props.setProperty("mail.imap.socketFactory.port", "993");
        props.setProperty("mail.imap.host", "outlook.office365.com");
        // 创建Session实例对象
        Session session = Session.getInstance(props);
        Store store = session.getStore(protocol);
        // 163邮箱程序登录属于第三方登录所以这里的密码是163给的授权密码而并非普通的登录密码
        store.connect(user, password);
        // 获得收件箱
        Folder inbox = store.getFolder("INBOX");
        // Folder.READ_ONLY:只读权限;Folder.READ_WRITE:可读可写(可以修改邮件的状态)
        inbox.open(Folder.READ_ONLY);

        // 搜索当天的邮件,得到收件箱中的所有邮件,并解析
        SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, this.getDayStart());
        SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, this.getDayEnd());
        SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, comparisonTermLe);
        Message[] messages = inbox.search(comparisonAndTerm);
        // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
        log.debug("未读邮件数: " + inbox.getUnreadMessageCount());
        // 获得收件箱中的邮件总数
        log.debug("邮件总数: " + inbox.getMessageCount());
        // 解析邮件消息体
        List<EmailMessageBO> emailMessageBOList = parseMessage(messages);

        //得到收件箱中的所有邮件并且删除邮件
//        deleteMessage(messages);

        //释放资源
        inbox.close(true);
        store.close();
        return emailMessageBOList;
    }

    /**
     * @param user
     * @param password
     * @return java.util.List<com.kbao.kbcassist.common.bean.EmailInfoBean>
     * @description exchange邮箱收件箱
     * @author wangzb01
     * @date 2020-12-16 16:54
     */
    private List<EmailMessageBO> receiveEmailExchange(String user, String password) throws Exception {
        //登录的账号和密码,账号一定是可以登录进去的账号,不一定是邮箱地址
        ExchangeService service = getExchangeService(user, password, null);
        // 连接收件箱 Bind to the Inbox. 绑定收件箱,同样可以绑定发件箱
        microsoft.exchange.webservices.data.core.service.folder.Folder inbox = microsoft.exchange.webservices.data.core.service.folder.Folder.bind(service, WellKnownFolderName.Inbox);
        int unreadCount = inbox.getUnreadCount();
        log.debug("未读邮件数:" + unreadCount);
        int totalCount = inbox.getTotalCount();
        log.debug("邮件总数:" + totalCount);
        // 循环获取邮件数量
        ItemView view = new ItemView(10);
        //按照时间顺序收取
        view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);

        // 搜索条件,搜索当天的邮件
        SearchFilter.SearchFilterCollection sf = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsGreaterThan(EmailMessageSchema.DateTimeReceived, this.getDayStart()),
                new SearchFilter.IsLessThan(EmailMessageSchema.DateTimeReceived, this.getDayEnd())
        );

        FindItemsResults<Item> findResults = service.findItems(inbox.getId(), sf, view);
        service.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties);
        List<EmailMessageBO> emailMessageBOList = new ArrayList<>();
        for (Item item : findResults.getItems()) {
            log.debug("------------------exchange邮箱邮件解析开始---------------------");
            EmailMessage msg = (EmailMessage) item;
            EmailMessageBO emailMessageBO = new EmailMessageBO();
            emailMessageBO.setMessageId(msg.getInternetMessageId());
            emailMessageBO.setSubject(msg.getSubject());
            emailMessageBO.setFrom(msg.getFrom().getAddress());
            emailMessageBO.setSentDate(getSentDate(msg.getDateTimeSent()));
            emailMessageBO.setContent(msg.getBody().toString());
            emailMessageBO.setRecipient(msg.getReceivedBy().getAddress());
            emailMessageBO.setSeen(msg.getIsRead());
            emailMessageBO.setHaveAttachment(msg.getHasAttachments());

            // 处理附件
            List<Attachment> attachmentList = msg.getAttachments().getItems();
            try {
                if (msg.getHasAttachments()) {
                    List<FileBean> fileBeanList = new ArrayList<>();
                    for (Attachment attachment : attachmentList) {
                        if (attachment instanceof FileAttachment) {
                            //接收邮件到临时目录
                            log.debug("解析exchange邮箱收件箱附件名称:{}", attachment.getName());
                            log.debug("----------解析exchange邮箱收件箱附件 并上传到阿里云OSS 开始----------");
                            File tempFile = new File(attachment.getName());
                            ((FileAttachment) attachment).load(tempFile.getPath());
                            // TODO 文件转文件流上传到阿里云OSS
                            FileBean fileBean = new FileBean();
                            fileBean.setFileName(attachment.getName());
                            fileBean.setFileUrl(tempFile.getAbsolutePath());
                            fileBeanList.add(fileBean);
                            // 删除临时存储文件
                            tempFile.delete();
                            log.debug("----------解析exchange邮箱收件箱附件 并上传到阿里云OSS 结束----------");
                        }
                    }
                    emailMessageBO.setFileBeanList(fileBeanList);
                    //删除邮件
                    //mail.delete(DeleteMode.HardDelete);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            emailMessageBOList.add(emailMessageBO);
            log.debug("------------------exchange邮箱邮件解析结束---------------------");


        }
        return emailMessageBOList;
    }


    /**
     * @param messages
     * @return java.util.List<com.kbao.kbcassist.email.model.EmailMessageBO>
     * @description 解析邮箱消息体列表
     * @author wangzb01
     * @date 2020-12-18 17:46
     */
    private List<EmailMessageBO> parseMessage(Message... messages) throws MessagingException, IOException {
        if (messages == null || messages.length < 1) {
            throw new MessagingException("未找到要解析的邮件!");
        }
        // 解析所有邮件
        List<EmailMessageBO> emailMessageBOList = new ArrayList<>();
        for (int i = 0, count = messages.length; i < count; i++) {
            MimeMessage msg = (MimeMessage) messages[i];
            //Start Content-type = text/html
            if (msg.isMimeType("text/*")) {
                log.debug("------------------解析第" + msg.getMessageNumber() + "封邮件开始---------------------");
                EmailMessageBO emailMessageBO = new EmailMessageBO();
                emailMessageBO.setMessageId(msg.getMessageID());
                emailMessageBO.setSubject(getSubject(msg));
                emailMessageBO.setFrom(getFrom(msg));
                emailMessageBO.setSentDate(getSentDate(msg.getSentDate()));
                String content = msg.getContent().toString();
                emailMessageBO.setContent(content);
                emailMessageBO.setRecipient(getReceiveAddress(msg, null));
                emailMessageBO.setSeen(isSeen(msg));
                // 是否包含附件
                boolean haveAttachment = haveAttachment(msg);
                emailMessageBO.setHaveAttachment(haveAttachment);
                if (haveAttachment) {
                    // 附件转成流传递存储
                    List<FileBean> fileBeanList = this.parseEmailFile(msg);
                    emailMessageBO.setFileBeanList(fileBeanList);
                }
                emailMessageBOList.add(emailMessageBO);
                System.out.println(emailMessageBO);
                log.debug("------------------解析第" + msg.getMessageNumber() + "封邮件结束---------------------");
            } else if (msg.isMimeType("multipart/*")) {
                log.debug("------------------解析第" + msg.getMessageNumber() + "封邮件开始---------------------");
                EmailMessageBO emailMessageBO = new EmailMessageBO();
                emailMessageBO.setMessageId(msg.getMessageID());
                emailMessageBO.setSubject(getSubject(msg));
                emailMessageBO.setFrom(getFrom(msg));
                emailMessageBO.setSentDate(getSentDate(msg.getSentDate()));
                MimeMultipart part = (MimeMultipart) msg.getContent();
                BodyPart body = null;
                for (int j = 0; j < part.getCount(); j++) {
                    body = part.getBodyPart(j);
                    if (body.isMimeType("text / *")) {
                        String content = body.getContent().toString();
                        emailMessageBO.setContent(content);
                        emailMessageBO.setRecipient(getReceiveAddress(msg, null));
                        emailMessageBO.setSeen(isSeen(msg));
                        // 是否包含附件
                        boolean haveAttachment = haveAttachment(msg);
                        emailMessageBO.setHaveAttachment(haveAttachment);
                        if (haveAttachment) {
                            // 附件转成流传递存储
                            List<FileBean> fileBeanList = this.parseEmailFile(msg);
                            emailMessageBO.setFileBeanList(fileBeanList);
                        }
                        emailMessageBOList.add(emailMessageBO);
                        System.out.println(emailMessageBO);
                    }
                }
                log.debug("------------------解析第" + msg.getMessageNumber() + "封邮件结束---------------------");
            }


        }
        return emailMessageBOList;
    }


    /**
     * @param messages
     * @return void
     * @description 解析邮件并删除
     * @author wangzb01
     * @date 2020-12-18 17:37
     */
    private void deleteMessage(Message... messages) throws MessagingException {
        if (messages == null || messages.length < 1) {
            throw new MessagingException("未找到要解析的邮件!");
        }
        // 解析所有邮件,并删除
        for (Message message : messages) {
            String subject = message.getSubject();
            // set the DELETE flag to true
            message.setFlag(Flags.Flag.DELETED, true);
            System.out.println("Marked DELETE for message: " + subject);
        }
    }

    /**
     * 获得邮件主题
     *
     * @param msg 邮件内容
     * @return 解码后的邮件主题
     */
    private String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
        return MimeUtility.decodeText(msg.getSubject());
    }

    /**
     * @param msg 邮件消息体
     * @return java.lang.String
     * @description 获取收件人邮箱
     * @author wangzb01
     * @date 2020-12-18 17:42
     */
    private String getFrom(MimeMessage msg) throws MessagingException {
        String from = "";
        Address[] addresses = msg.getFrom();
        if (addresses.length < 1) {
            throw new MessagingException("没有发件人!");
        }
        InternetAddress address = (InternetAddress) addresses[0];
        from = address.getAddress();
        return from;
    }

    /**
     * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人
     * <p>Message.RecipientType.TO  收件人</p>
     * <p>Message.RecipientType.CC  抄送</p>
     * <p>Message.RecipientType.BCC 密送</p>
     *
     * @param msg  邮件内容
     * @param type 收件人类型
     * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ...
     * @throws MessagingException
     */
    private String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
        StringBuffer receiveAddress = new StringBuffer();
        Address[] addresss = null;
        if (type == null) {
            addresss = msg.getAllRecipients();
        } else {
            addresss = msg.getRecipients(type);
        }

        if (addresss == null || addresss.length < 1) {
            throw new MessagingException("没有收件人!");
        }
        for (Address address : addresss) {
            InternetAddress internetAddress = (InternetAddress) address;
            receiveAddress.append(internetAddress.toUnicodeString()).append(",");
        }

        receiveAddress.deleteCharAt(receiveAddress.length() - 1); //删除最后一个逗号

        return receiveAddress.toString();
    }

    /**
     * 获得邮件发送时间
     *
     * @param date 邮件时间
     * @return LocalDateTime
     * @throws MessagingException
     */
    private LocalDateTime getSentDate(Date date) {
        if (date == null) {
            return null;
        }
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }

    /**
     * 判断邮件中是否包含附件
     *
     * @param part 邮件内容
     * @return 邮件中存在附件返回true,不存在返回false
     * @throws MessagingException
     * @throws IOException
     */
    private boolean haveAttachment(Part part) throws MessagingException, IOException {
        boolean flag = false;
        if (part.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    flag = haveAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("application") != -1) {
                        flag = true;
                    }

                    if (contentType.indexOf("name") != -1) {
                        flag = true;
                    }
                }

                if (flag) {
                    break;
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            flag = haveAttachment((Part) part.getContent());
        }
        return flag;
    }

    /**
     * 判断邮件是否已读
     *
     * @param msg 邮件内容
     * @return 如果邮件已读返回true, 否则返回false
     * @throws MessagingException
     */
    private boolean isSeen(MimeMessage msg) throws MessagingException {
        return msg.getFlags().contains(Flags.Flag.SEEN);
    }

    /**
     * 判断邮件是否需要阅读回执
     *
     * @param msg 邮件内容
     * @return 需要回执返回true, 否则返回false
     * @throws MessagingException
     */
    private boolean isReplySign(MimeMessage msg) throws MessagingException {
        boolean replySign = false;
        String[] headers = msg.getHeader("Disposition-Notification-To");
        if (headers != null) {
            replySign = true;
        }
        return replySign;
    }

    /**
     * 获得邮件的优先级
     *
     * @param msg 邮件内容
     * @return 1(High):紧急  3:普通(Normal)  5:低(Low)
     * @throws MessagingException
     */
    private String getPriority(MimeMessage msg) throws MessagingException {
        String priority = "普通";
        String[] headers = msg.getHeader("X-Priority");
        if (headers != null) {
            String headerPriority = headers[0];
            if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1) {
                priority = "紧急";
            } else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1) {
                priority = "低";
            } else {
                priority = "普通";
            }
        }
        return priority;
    }

    /**
     * 获得邮件文本内容
     *
     * @param part    邮件体
     * @param content 存储邮件文本内容的字符串
     * @throws MessagingException
     * @throws IOException
     */
    private void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
        //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part) part.getContent(), content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart, content);
            }
        }
    }

    /**
     * @param part
     * @return java.util.List<com.kbao.kbcassist.common.sub.OssFileMsg>
     * @description 解析163、exchange邮箱附件并上传到OSS上存储
     * @author wangzb01
     * @date 2020-12-18 17:20
     */
    private List<FileBean> parseEmailFile(Part part) throws MessagingException, IOException {
        List<FileBean> fileBeanList = new ArrayList<>();
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
            //复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                //获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                //某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    this.getEmailFileUploadOss(fileBeanList, bodyPart);
                } else if (bodyPart.isMimeType("multipart/*")) {
                    this.parseEmailFile(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        this.getEmailFileUploadOss(fileBeanList, bodyPart);
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            this.parseEmailFile((Part) part.getContent());
        }
        return fileBeanList;
    }

    /**
     * @param fileBeanList
     * @param bodyPart
     * @return void
     * @description 解析163、outlook收件箱附件 并上传到阿里云OSS
     * @author wangzb01
     * @date 2020-12-18 17:28
     */
    private void getEmailFileUploadOss(List<FileBean> fileBeanList, BodyPart bodyPart) throws MessagingException, IOException {
        log.debug("解析163、outlook收件箱附件名称:{}", decodeText(bodyPart.getFileName()));
        log.debug("----------解析163、outlook收件箱附件 并上传到阿里云OSS 开始----------");
        // TODO 附件流文件上传到阿里云OSS
        FileBean fileBean = new FileBean();
        fileBean.setFileName(decodeText(bodyPart.getFileName()));
        fileBean.setFileUrl("阿里云OSS文件访问路径");
        fileBeanList.add(fileBean);
        log.debug("----------解析163、outlook收件箱附件 并上传到阿里云OSS 结束----------");
    }


    /**
     * 文本解码
     *
     * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
     * @return 解码后的文本
     * @throws UnsupportedEncodingException
     */
    private String decodeText(String encodeText) throws UnsupportedEncodingException {
        if (encodeText == null || "".equals(encodeText)) {
            return "";
        } else {
            return MimeUtility.decodeText(encodeText);
        }
    }


    /**
     * @param user     账号
     * @param password 密码
     * @param domain   认证信息,可不填
     * @return microsoft.exchange.webservices.data.core.ExchangeService
     * @description 创建exchange邮箱服务
     * @author wangzb01
     * @date 2020-12-15 16:46
     */
    private ExchangeService getExchangeService(String user, String password, String domain) {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
        //用户认证信息
        ExchangeCredentials credentials;
        if (domain == null) {
            credentials = new WebCredentials(user, password);
        } else {
            credentials = new WebCredentials(user, password, domain);
        }
        service.setCredentials(credentials);
        try {
            service.setUrl(new URI("https://outlook.sos.eu/ews/exchange.asmx"));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return service;
    }

    /**
     * @param content
     * @return java.lang.String
     * @description 邮件HTML格式转纯文本
     * @author wangzb01
     * @date 2020-12-15 17:19
     */
    private String getContentFromHtml(String content) {
        content = content.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
        content = content.replaceAll("<a>\\s*|\t|\r|\n</a>", "");
        content = content.replaceAll("&nbsp;", "");
        content = content.replaceAll("\n", "");
        return content;
    }


    /**
     * @param emailSendBO
     * @return void
     * @description 163邮箱发邮件
     * @author wangzb01
     * @date 2020-12-16 17:07
     */
    private void sendEmail163(EmailSendBO emailSendBO) {
        // 不同邮箱对应不同的服务器协议地址和端口号
        String smtpHost = "smtp.163.com";
        String popPort = "25";
        final Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.store.protocol", "smtp");
        props.put("mail.smtp.port", popPort);
        //开启SSL
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.port", popPort);
        props.put("mail.smtp.socketFactory.fallback", "false");
        try {
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 账号密码验证
                    return new PasswordAuthentication(emailSendBO.getFrom(), emailSendBO.getPassword());
                }
            });
            session.setDebug(true);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(session);
            // 设置发件人
            InternetAddress form = new InternetAddress(emailSendBO.getFrom());
            message.setFrom(form);
            // 设置收件人
            InternetAddress toAddress = new InternetAddress(emailSendBO.getRecipient());
            message.setRecipient(Message.RecipientType.TO, toAddress);
            //抄送人
            if (StringUtils.isNotBlank(emailSendBO.getRecipientCc())) {
                InternetAddress recipientCC = new InternetAddress(emailSendBO.getRecipientCc());
                message.setRecipient(Message.RecipientType.CC, recipientCC);
            }
            // 设置邮件标题
            message.setSubject(emailSendBO.getSubject());
            // 是否带附件发送
            if (!emailSendBO.getFileBeanList().isEmpty()) {
                // 创建多重消息
                Multipart multipart = new MimeMultipart();
                // 创建普通消息部分
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(emailSendBO.getContent());
                // 设置多重消息的文本消息部分
                multipart.addBodyPart(messageBodyPart);
                // 设置邮件内容体
                for (FileBean fileBean : emailSendBO.getFileBeanList()) {
                    // 发送多个附件部分
                    MimeBodyPart mimeBodyPart = new MimeBodyPart();
                    // 设置附件源文件URL
                    URL url = new URL(fileBean.getFileUrl());
                    DataSource source = new URLDataSource(url);
                    mimeBodyPart.setDataHandler(new DataHandler(source));
                    // 设置附件名称
                    mimeBodyPart.setFileName(MimeUtility.encodeText(fileBean.getFileName()));
                    multipart.addBodyPart(mimeBodyPart);
                }
                // 设置最终的邮件
                message.setContent(multipart);
            } else {
                // 设置邮件的内容体
                message.setContent(emailSendBO.getContent(), "text/html;charset=UTF-8");
            }

            // 发送邮件
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送邮件异常:{}", e.getMessage());
        }

    }

    /**
     * @param emailSendBO
     * @return void
     * @description outlook邮箱发邮件
     * @author wangzb01
     * @date 2020-12-16 17:08
     */
    private void sendEmailOutlook(EmailSendBO emailSendBO) {
        // 不同邮箱对应不同的服务器协议地址和端口号
        String smtpHost = "smtp-mail.outlook.com";
        String popPort = "587";
        final Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.store.protocol", "smtp");
        props.put("mail.smtp.port", popPort);
        //开启SSL
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.port", popPort);
        props.put("mail.smtp.socketFactory.fallback", "false");
        try {
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 账号密码验证
                    return new PasswordAuthentication(emailSendBO.getFrom(), emailSendBO.getPassword());
                }
            });
            session.setDebug(true);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(session);
            // 设置发件人
            InternetAddress form = new InternetAddress(emailSendBO.getFrom());
            message.setFrom(form);
            // 设置收件人
            InternetAddress toAddress = new InternetAddress(emailSendBO.getRecipient());
            message.setRecipient(Message.RecipientType.TO, toAddress);
            //抄送人
            if (StringUtils.isNotBlank(emailSendBO.getRecipientCc())) {
                InternetAddress recipientCC = new InternetAddress(emailSendBO.getRecipientCc());
                message.setRecipient(Message.RecipientType.CC, recipientCC);
            }
            // 设置邮件标题
            message.setSubject(emailSendBO.getSubject());
            // 是否带附件发送
            if (!emailSendBO.getFileBeanList().isEmpty()) {
                // 创建多重消息
                Multipart multipart = new MimeMultipart();
                // 创建普通消息部分
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(emailSendBO.getContent());
                // 设置多重消息的文本消息部分
                multipart.addBodyPart(messageBodyPart);
                // 设置邮件内容体
                for (FileBean fileBean : emailSendBO.getFileBeanList()) {
                    // 发送多个附件部分
                    MimeBodyPart mimeBodyPart = new MimeBodyPart();
                    // 设置附件源文件URL
                    try {
                        URL url = new URL(fileBean.getFileUrl());
                        url.openStream();
                        DataSource source = new URLDataSource(url);
                        mimeBodyPart.setDataHandler(new DataHandler(source));
                        // 设置附件名称
                        mimeBodyPart.setFileName(MimeUtility.encodeText(fileBean.getFileName()));
                        multipart.addBodyPart(mimeBodyPart);
                    } catch (IOException e) {
                        log.info("有问题的邮件附件");
                        e.printStackTrace();
                    }
                }
                // 设置最终的邮件
                message.setContent(multipart);
            } else {
                // 设置邮件的内容体
                message.setContent(emailSendBO.getContent(), "text/html;charset=UTF-8");
            }
            // 发送邮件
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送邮件异常:{}", e.getMessage());
        }
    }

    /**
     * @param emailSendBO
     * @return void
     * @description exchange邮箱发邮件
     * @author wangzb01
     * @date 2020-12-16 16:55
     */
    private void sendEmailExchange(EmailSendBO emailSendBO) {
        // Exchange服务器版本。
        ExchangeService exchangeService = new ExchangeService(ExchangeVersion.Exchange2010);

        // 要在MS Exchange服务器上签名的凭据。
        ExchangeCredentials exchangeCredentials = new WebCredentials(emailSendBO.getFrom(), emailSendBO.getPassword(), null);
        exchangeService.setCredentials(exchangeCredentials);

        // 邮箱的exchange web服务的URL
        try {
            exchangeService.setUrl(new URI("https://outlook.sos.eu/ews/exchange.asmx"));
        } catch (URISyntaxException ex) {
            log.error("创建与服务端的连接发生异常", ex);
            if (exchangeService != null) {
                exchangeService.close();
            }
        }

        // 设置邮件信息
        EmailMessage emailMessage = null;
        try {
            emailMessage = new EmailMessage(exchangeService);
            emailMessage.setSubject(emailSendBO.getSubject());
            emailMessage.setBody(MessageBody.getMessageBodyFromText(emailSendBO.getContent()));
        } catch (Exception ex) {
            log.error("设置邮件发生异常", ex);
        }

        // 设置收件人
        try {
            emailMessage.getToRecipients().add(emailSendBO.getRecipient());
        } catch (ServiceLocalException ex) {
            log.error("设置邮件收件人发生异常.", ex);
        }

        // 设置抄送人
//        for (String recipient : recipientCc) {
//            try {
//                emailMessage.getCcRecipients().add(recipient);
//            } catch (ServiceLocalException ex) {
//                log.error("设置邮件抄送人发生异常.", ex);
//            }
//        }

        // 设置邮件密送人
//        for (String recipient : recipientBcc) {
//            try {
//                emailMessage.getBccRecipients().add(recipient);
//            } catch (ServiceLocalException ex) {
//                log.error("设置邮件密送人发生异常.", ex);
//            }
//        }

        // 设置附件
        if (!emailSendBO.getFileBeanList().isEmpty()) {
            for (FileBean fileBean : emailSendBO.getFileBeanList()) {
                try {
                    InputStream inputStream = this.urlToInputStream(fileBean.getFileUrl());
                    emailMessage.getAttachments().addFileAttachment(fileBean.getFileName(), inputStream);
                } catch (ServiceLocalException ex) {
                    log.error("设置邮件附件发生异常", ex);
                }
            }
        }

        try {
            emailMessage.send();
            log.info("邮件发送成功.");
        } catch (Exception ex) {
            log.error("邮件发送异常.", ex);
        }
    }

    /**
     * 通过图片url返回IO流
     *
     * @param path
     * @return
     */
    private InputStream urlToInputStream(String path) {
        URL url = null;
        InputStream is = null;
        try {
            url = new URL(path);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            //利用HttpURLConnection对象,我们可以从网络中获取网页数据.
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            //得到网络返回的输入流
            is = conn.getInputStream();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }

}

邮件收发公共服务层接口
package com.example.demo.service;


import com.example.demo.model.EmailMessageBO;
import com.example.demo.model.EmailSendBO;

import java.util.List;

/**
 * @className: EmailCommonService
 * @description: 邮件公共服务层
 * @author: wangzb01
 * @version: V1.0
 * @since: V1.0
 * @className: 2020-12-18 8:56
 */
public interface EmailCommonService {

    /**
     * @param user      邮箱地址
     * @param password  邮箱密码
     * @param emailType 邮箱类型
     * @return java.util.List<com.kbao.kbcassist.common.bean.EmailInfoBean>
     * @description 接收邮件公共方法
     * @author wangzb01
     * @date 2020-12-18 9:34
     */
    List<EmailMessageBO> receive(String user, String password, String emailType);

    /**
     * @param emailSendBO
     * @return void
     * @description 发送邮件公共方法
     * @author wangzb01
     * @date 2020-12-23 9:33
     */
    void send(EmailSendBO emailSendBO);
}
发送邮件业务参数对象
package com.example.demo.model;

import lombok.Data;

import java.util.List;

/**
 * @className: EmailSendBO
 * @description: 发送邮件业务参数对象
 * @author: wangzb01
 * @version: V1.0
 * @since: V1.0
 * @className: 2020-12-23 9:59
 */
@Data
public class EmailSendBO {

    /**
     * 发件人
     * test@163.com
     */
    private String from;

    /**
     * 邮箱密码
     * test
     */
    private String password;

    /**
     * 收件人
     * 12@163.com;21@163.com
     */
    private String recipient;

    /**
     * 抄送人
     * 3344@163.com;5566@163.com
     */
    private String recipientCc;

    /**
     * 邮件标题
     * 这是一封测试邮件
     */
    private String subject;

    /**
     * 邮件内容
     * 测试内容无需回复
     */
    private String content;

    /**
     * 邮箱类型(163邮箱,outlook邮箱,exchange邮箱)
     * outlook
     */
    private String emailType;

    /**
     * 邮件附件集合
     * 文件集合
     */
    private List<FileBean> fileBeanList;

}
文件基础对象
package com.example.demo.model;

import lombok.Data;

/**
 * @className: FileBean
 * @description: 文件基础对象
 * @author: wangzb01
 * @version: V1.0
 * @since: V1.0
 * @className: 2020-12-17 9:27
 */
@Data
public class FileBean {

    /**
     * 文件名
     * 保险公司.jpg
     */
    private String fileName;

    /**
     * 文件URL
     * https://oss-test-hd2-01.oss-cn-shanghai-finance-1.aliyuncs.com/assist_sta_uat/test/2020120709480951.jpg
     */
    private String fileUrl;

}
邮件消息体业务对象
package com.example.demo.model;

import lombok.Data;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @className: EmailMessage
 * @description: 邮件消息体业务对象
 * @author: wangzb01
 * @version: V1.0
 * @since: V1.0
 * @className: 2020-12-18 10:49
 */
@Data
public class EmailMessageBO {

    /**
     * 邮件ID
     */
    private String messageId;

    /**
     * 邮件ID
     */
    private String subject;

    /**
     * 发件人
     */
    private String from;

    /**
     * 邮件发送时间
     */
    private LocalDateTime sentDate;

    /**
     * 收件人
     */
    private String recipient;

    /**
     * 邮件正文
     */
    private String content;

    /**
     * 邮件是否已读
     */
    private Boolean seen;

    /**
     * 邮件是否包含附件
     */
    private Boolean haveAttachment;

    /**
     * 文件集合
     */
    private List<FileBean> fileBeanList;
}

本文地址:https://blog.csdn.net/flyingwzb/article/details/112677882