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

邮件发送与接收,支持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.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*/@Overridepublic 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;}}@Overridepublic 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为falseprops.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 文件转文件流上传到阿里云OSSFileBean 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/htmlif (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 truemessage.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 附件流文件上传到阿里云OSSFileBean 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);//开启SSLprops.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() {@Overrideprotected 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();// 设置附件源文件URLURL 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);//开启SSLprops.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() {@Overrideprotected 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();// 设置附件源文件URLtry {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服务的URLtry {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;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/37998.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

手把手教你设置foxmail客户端支持收发outlook.com邮箱里的邮件

话不多说&#xff0c;入正题啦1&#xff0c;下载安装foxmail客户端&#xff0c;也有免安装版的&#xff0c;这里不作介绍。地址&#xff1a;http://fox.foxmail.com.cn/2&#xff0c;打开foxmail软件&#xff0c;点击“工具”— 帐号管理 3&#xff0c;点击左下角的“新建”按钮…

举个栗子~Tableau 技巧(244):用和弦图(Chord diagram)呈现数据关系

关于和弦图 和弦图&#xff08;Chord diagram&#xff09;常用来表示数据之间的相互关系。数据点沿着圆圈分布&#xff0c;通过点和点之间相互连接的弧线来呈现相互之间的关系。和弦图从视觉上来说比较美观&#xff0c;数据呈现又很直观&#xff0c;所以深受数据粉喜爱。 之前…

HuggingGPT 火了:一个 ChatGPT 控制所有 AI 模型,自动帮人完成 AI 任务,网友:留口饭吃吧..._QbitAl 的博客 - CSDN 博客

转载自&#xff1a;https://blog.csdn.net/QbitAI/article/details/129942855 丰色 发自 凹非寺 量子位 | 公众号 QbitAI 最强组合&#xff1a;HuggingFaceChatGPT —— HuggingGPT&#xff0c;它来了&#xff01; 只要给定一个 AI 任务&#xff0c;例如 “下面这张图片里…

“寻找贾维斯”简史

可能人人都希望自己有个“贾维斯”。 虽然已经退出漫威电影很多年&#xff0c;但是我们还是能够记起那个钢铁侠战衣里无所不能的AI助手。独特的幽默、优雅的语调&#xff0c;以及非常靠谱的人设&#xff0c;让无数科幻迷对这个看不见听得到的角色产生了无尽好感。 对贾维斯的…

jarvis贾维斯语音_保罗·贾维斯(Paul Jarvis)可以教给我们的建立业务的知识

jarvis贾维斯语音 想要在八到九个月内赚足够的钱&#xff0c;让您在一年中的剩余时间里做任何想做的事吗&#xff1f; (Want to make enough money in eight or nine months to last you for the rest of the year doing whatever the heck you want?) So do we. That’s why …

JARVIS(贾维斯)来了,科技改变生活

微软开源地址 https://github.com/microsoft/JARVIS 后续可能性&#xff1a; 每个人都有一个自己的AI助理提高生活便捷性学习知识的速度更快云助理 && 家用私人部署助理

谷歌拼音 输入法设置

谷歌拼音输入法 2.7&#xff0c;默认的是半角字符&#xff0c;中文标点 为了防止 以后 在输入代码的时候&#xff0c;出错&#xff0c;中文和 英文 都用 英文标点吧。

基于ubuntu20.4安装谷歌拼音中文输入法

1.首先命令行安装汉语语言包 sudo apt-get install language-pack-zh-hans 执行该命令后&#xff0c;系统就会自动安装所需要的汉语语言包 图1 安装汉语语言包 2.然后命令行安装谷歌拼音输入法 sudo apt-get install fcitx-googlepinyin 执行该命令后&#xff0c;系统就会自…

google输入法PK搜狗输入法

往往一个人用某个软件用的时间久了,久而久之就会形成一种习惯,不再探索或关注其他的类似的软件。造成的后果就是你只知道一款软件就这些功能,其余的知之甚少,就如同今天,看到别人输入法的皮肤特别漂亮,于是就想搜狗有这么漂亮的皮肤。问过后才知道人家用的是个google的拼…

Ubuntu20.04 安装谷歌拼音(googlepinyin)输入法

1.更新一下 sudo apt update 2.安装Fcitx sudo apt install fcitx如果有报错&#xff0c;执行下面命令 sudo apt install fcitx --fix-missing 3.命令行输入&#xff1a; im-config 弹出页面 &#xff0c;选择ok&#xff0c;然后选择yes按钮&#xff0c;最后选择fcitx。…

谷歌拼音输入法PinyinIME源码修改----随着Setting中中英文的切换对应改变软键盘中英文输入且字符变换

项目中使用的是Google的输入法&#xff1a;谷歌拼音输入法&#xff0c;即PinyinIME。 客户提出需求&#xff1a;需要在Setting中切换中英文的时候&#xff0c;输入法对应成中英文输入&#xff0c;并且字符也对应成中英文&#xff0c;即Setting中设置为中文的时候&#xff0c;输…

安装google输入法后,左shift键不能切换中英文

解决方法 打开fcitx配置页 如图应有两个选项&#xff0c;即google拼音和 键盘英语&#xff0c;如不足&#xff0c;则选择左下角添加。 此后虽然可切换中英文&#xff0c;但是打开一个新页面后只按shift键却不能正常切换中英&#xff0c;必须要ctrl加空格后才能切换&#xff0c…

写在发现谷歌拼音输入法网站消失的今天

今天偶然发现谷歌拼音输入法PC版的网页消失了&#xff0c;我想以后可能都不会有了&#xff0c;除非谷歌重返大陆。 PC端的谷歌拼音输入法从2013年就已经停止更新&#xff0c;但这并不妨碍我继续使用它&#xff0c;之前它的官网一直都在&#xff0c;也提供下载。 之所以喜欢这…

Google推出拼音输入法了!

网址&#xff1a; http://tools.google.com/pinyin 下载地址&#xff1a;http://dl.google.com/pinyin/GooglePinyinInstaller.exe 用了一下&#xff0c;感觉挺好用的&#xff0c;同志们有兴趣的话&#xff0c;也试试看吧。恩 聪明的谷歌拼音输入法五大特色&#xff1a; …

网页上使用的输入法——Google Transliteration

简介 输入法通常是装在PC上用的&#xff0c;但是API有关部门的童鞋发现了专门在网页上用的输入法&#xff08;见上图&#xff09;。 这个插件的作用&#xff0c;按照官方说法&#xff1a; 您可以使用 Google 输入工具在网络中的任何位置以所选语言轻松地输入内容。 此接口采集自…

Python实战之12306抢票

实战&#xff1a;12306抢票 注意&#xff1a;代码运行之后&#xff0c;需要手动使用12306APP扫码登录 代码如下&#xff1a; import csv from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import…

python实现12306全自动抢票

这个脚本目前只能刷一趟车的&#xff0c;人数可以是多个&#xff0c;支持选取作为类型等。 实现思路是splinter.browser模拟浏览器登陆和操作&#xff0c;由于12306的验证码不好自动识别&#xff0c;所以&#xff0c;验证码需要用户进行手动识别&#xff0c;并进行登陆操作&am…

小年到了,回家抢票太难,用Python做个脚本12306自动查票以及自动购票....

今天就是小年了&#xff0c;听说还有人买不到票&#xff1f;不要慌&#xff0c;今天咱们来用Python做一个自动查票抢票的脚本&#xff0c;24小时抢票&#xff0c;谁抢的过你&#xff01;源码包已打包文件夹获取方式&#xff1a;点击这里【 Python全套资料】 即可获取。 准备工作…

C++写的12306抢票软件

写在前面的话 每年逢年过节&#xff0c;一票难求读者肯定不陌生。这篇文章&#xff0c;我们带领读者从零实现一款12306刷票软件&#xff0c;其核心原理还是通过发送http请求模拟登录12306网站的购票的过程&#xff0c;最后买到票。 郑重申明一下&#xff1a;这里介绍的技术仅供…

Python抢票神器

又到了一年一度的抢票大战&#xff0c;本来就辛苦劳累了一年&#xff0c;想着可以早点订到票跟家里人团聚。所以&#xff0c;许多人宁愿多花些钱去找黄牛买票。 但今年各种抢票软件的横行&#xff0c;还有官方出的加速包&#xff0c;导致连黄牛都不敢保证能买到票。你无奈的只能…