java通过Exchange协议发送邮件

1、由于公司邮箱采用微软的,所以之前使用STMP协议发送业务告知邮件的业务代码需要变更。首先需要在项目引入以下Jar包

	
		
			com.microsoft.ews-java-api
			ews-java-api
			2.0
		

2、下面是实现代码

 

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gfa4j.utils.ResultUtils;

import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;

public class ExchangeClient {

	Logger logger = LoggerFactory.getLogger(ExchangeClient.class);
	
	private final String hostname;
    private final ExchangeVersion exchangeVersion;
    private final String domain;
    private final String username;
    private final String password;
    private final String subject;
    private final String recipientTo;
    private final List recipientCc;
    private final List recipientBcc;
    private final List attachments;
    private final String message;

    private ExchangeClient(ExchangeClientBuilder builder) {
        this.hostname = builder.hostname;
        this.exchangeVersion = builder.exchangeVersion;
        this.domain = builder.domain;
        this.username = builder.username;
        this.password = builder.password;
        this.subject = builder.subject;
        this.recipientTo = builder.recipientTo;
        this.recipientCc = builder.recipientCc;
        this.recipientBcc = builder.recipientBcc;
        this.attachments = builder.attachments;
        this.message = builder.message;
    }

    public static class ExchangeClientBuilder {

        private String hostname;
        private ExchangeVersion exchangeVersion;
        private String domain;
        private String username;
        private String password;
        private String subject;
        private String recipientTo;
        private List recipientCc;
        private List recipientBcc;
        private List attachments;
        private String message;

        public ExchangeClientBuilder() {
            this.exchangeVersion = ExchangeVersion.Exchange2010_SP1;
            this.hostname = "";
            this.username = "";
            this.password = "";
            this.subject = "";
            this.recipientTo = "";
            this.recipientCc = new ArrayList<>(0);
            this.recipientBcc = new ArrayList<>(0);
            this.attachments = new ArrayList<>(0);
            this.message = "";
        }

        /**
         * @Desc Exchange Web服务的主机名
         * @param hostname
         * @return
         */
        public ExchangeClientBuilder hostname(String hostname) {
            this.hostname = hostname;
            return this;
        }

        /**
         * @Desc Exchange Web服务器版本。
         * @param exchangeVersion
         * @return
         */
        public ExchangeClientBuilder exchangeVersion(ExchangeVersion exchangeVersion) {
            this.exchangeVersion = exchangeVersion;
            return this;
        }

        /**
         * @Desc smtp服务器的域。
         * @param domain
         * @return
         */
        public ExchangeClientBuilder domain(String domain) {
            this.domain = domain;
            return this;
        }

        /**
         * @Desc MS Exchange Smtp服务器的用户名 发送用户
         * @param username
         * @return
         */
        public ExchangeClientBuilder username(String username) {
            this.username = username;
            return this;
        }

        /**
         * @Desc 发送用户的密码
         * @param password
         * @return
         */
        public ExchangeClientBuilder password(String password) {
            this.password = password;
            return this;
        }

        /**
         * @Desc 邮件主题
         * @param subject
         * @return
         */
        public ExchangeClientBuilder subject(String subject) {
            this.subject = subject;
            return this;
        }

        /**
         * @Desc 收件人
         * @param recipientTo
         * @return
         */
        public ExchangeClientBuilder recipientTo(String recipientTo) {
            this.recipientTo = recipientTo;
            return this;
        }

        /**
         * @Desc 抄送人
         * @param recipientCc
         * @param recipientsCc
         * @return
         */
        public ExchangeClientBuilder recipientCc(String recipientCc, String... recipientsCc) {
            // Prepare the list.
            List recipients = new ArrayList<>(1 + recipientsCc.length);
            recipients.add(recipientCc);
            recipients.addAll(Arrays.asList(recipientsCc));
            // Set the list.
            this.recipientCc = recipients;
            return this;
        }

        /**
         * @Desc 抄送人
         * @param recipientCc
         * @return
         */
        public ExchangeClientBuilder recipientCc(List recipientCc) {
            this.recipientCc = recipientCc;
            return this;
        }

        /**
         * @Desc 密送人
         * @param recipientBcc
         * @param recipientsBcc
         * @return
         */
        public ExchangeClientBuilder recipientBcc(String recipientBcc, String... recipientsBcc) {
            // Prepare the list.
            List recipients = new ArrayList<>(1 + recipientsBcc.length);
            recipients.add(recipientBcc);
            recipients.addAll(Arrays.asList(recipientsBcc));
            // Set the list.
            this.recipientBcc = recipients;
            return this;
        }

        /**
         * @Desc 密送人
         * @param recipientBcc
         * @return
         */
        public ExchangeClientBuilder recipientBcc(List recipientBcc) {
            this.recipientBcc = recipientBcc;
            return this;
        }

        /**
         * @Desc 附件
         * @param attachment
         * @param attachments
         * @return
         */
        public ExchangeClientBuilder attachments(String attachment, String... attachments) {
            // Prepare the list.
            List attachmentsToUse = new ArrayList<>(1 + attachments.length);
            attachmentsToUse.add(attachment);
            attachmentsToUse.addAll(Arrays.asList(attachments));
            // Set the list.
            this.attachments = attachmentsToUse;
            return this;
        }

        /**
         * @Desc 附件
         * @param attachments
         * @return
         */
        public ExchangeClientBuilder attachments(List attachments) {
            this.attachments = attachments;
            return this;
        }

        /**
         * @Desc 邮件正文
         * @param message
         * @return
         */
        public ExchangeClientBuilder message(String message) {
            this.message = message;
            return this;
        }

        /**
         * @Desc 创建邮件
         * @return
         */
        public ExchangeClient build() {
            return new ExchangeClient(this);
        }
    }

    /**
     * @Desc 发送邮件
     * @return
     */
    public Map sendExchange() {
        // Exchange服务器版本。
        ExchangeService exchangeService = new ExchangeService(exchangeVersion);

        // 要在MS Exchange服务器上签名的凭据。
        ExchangeCredentials exchangeCredentials = new WebCredentials(username, password, domain);
        exchangeService.setCredentials(exchangeCredentials);

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

        // 设置邮件信息
        EmailMessage emailMessage;
        try {
            emailMessage = new EmailMessage(exchangeService);
            emailMessage.setSubject(subject);
            emailMessage.setBody(MessageBody.getMessageBodyFromText(message));
        } catch (Exception ex) {
            logger.error("设置邮件发生异常", ex);
            return ResultUtils.getFaildResultData("设置邮件发生异常");
        }

        // 设置收件人
        try {
            emailMessage.getToRecipients().add(recipientTo);
        } catch (ServiceLocalException ex) {
            logger.error("设置邮件收件人发生异常.", ex);
            return ResultUtils.getFaildResultData("设置邮件收件人发生异常");
        }

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

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

        // 设置附件
        for (String attachmentPath : attachments) {
            try {
                emailMessage.getAttachments().addFileAttachment(attachmentPath);
            } catch (ServiceLocalException ex) {
                logger.error("设置邮件附件发生异常", ex);
                return ResultUtils.getFaildResultData("设置邮件附件发生异常");
            }
        }

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

}

3、测试用例

 

import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

/**
 * 邮件发送工具类
 *
 */
public class MailTool {
	private static final Logger logger = LoggerFactory.getLogger(MailTool.class);
	private static String PROPERTIES_CONFIG = "mailConfig.properties";
	private static String HOSTNAME = "mail.xxxx.com";
    private static String USERNAME="cwzx";
    private static String PASSWORD ="xxxx";
    private static Properties properties;
	private static String[] ERRORMSG_RECIPIENTCCS = {};
	public static String DOMAIN_NAME;

	  

	/*static {
		changeSender();
	}

	public static boolean changeSender() {
		properties = new Properties();
		InputStream inputStream = null;
		try {
			inputStream = MailTool.class.getClassLoader().getResourceAsStream(PROPERTIES_CONFIG);
			properties.load(inputStream);
			inputStream.close();
			HOSTNAME = properties.getProperty("mailHost");
			USERNAME = properties.getProperty("username");
			PASSWORD = properties.getProperty("password");
			DOMAIN_NAME = properties.getProperty("domain_name");
		} catch (IOException e) {
			logger.error("读取配置文件错误", e);
			return false;
		}
		return true;
	}
*/
	public static Map sendMail(String to, String subject, String message) {
		ExchangeClient exchangeClient = new ExchangeClient.ExchangeClientBuilder()
				.hostname(HOSTNAME)
				.exchangeVersion(ExchangeVersion.Exchange2010)
				.username(USERNAME)
				.password(PASSWORD)
				.subject(subject)
				.message(message)
				.recipientTo(to)
				.build();
		return exchangeClient.sendExchange();
	}
	
/*	public static void sendErrorMsg(String subject, String message) {
		ExchangeClient exchangeClient = new ExchangeClient.ExchangeClientBuilder()
				.hostname(HOSTNAME)
				.exchangeVersion(ExchangeVersion.Exchange2010)
				.username(USERNAME)
				.password(PASSWORD)
				.subject(subject)
				.message(message)
				.recipientTo(ERRORMSG_RECIPIENT)
				.recipientCc(Arrays.asList(ERRORMSG_RECIPIENTCCS))
				.build();
		exchangeClient.sendExchange();
	}*/


	public static void main(String[] args) {
		StringBuilder builder = new StringBuilder();
		builder.append("尊敬的客户:
"); builder.append("       您好!
"); builder.append("       "); builder.append("您申请的电子发票已经开具,查看发票请点击附件,发票详情:
"); builder.append("       "); builder.append("发票抬头:XX
"); builder.append("       "); builder.append("发票号码:729020
"); builder.append("       "); builder.append("发票金额:45.00
"); builder.append("       "); builder.append("   "); builder.append("2、23504480563
"); builder.append("



"); builder.append("       "); builder.append("       "); builder.append("点击以下链接下载电子发票(PDF格式):
"); builder.append("       "); builder.append("下载点在发票:"); builder.append("http://2u35ou4t5it-5iy"); ExchangeClient exchangeClient = new ExchangeClient.ExchangeClientBuilder() .hostname(HOSTNAME) .exchangeVersion(ExchangeVersion.Exchange2010) .username(USERNAME) .password(PASSWORD) .subject("电子发票通知") .message(builder.toString()) .recipientTo(" ") .build(); exchangeClient.sendExchange(); } }

 

你可能感兴趣的:(java)