java通过Exchange协议发送邮件

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

	<!-- 微软邮箱 -->
		<dependency>
			<groupId>com.microsoft.ews-java-api</groupId>
			<artifactId>ews-java-api</artifactId>
			<version>2.0</version>
		</dependency>

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<String> recipientCc;
    private final List<String> recipientBcc;
    private final List<String> 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<String> recipientCc;
        private List<String> recipientBcc;
        private List<String> 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<String> 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<String> recipientCc) {
            this.recipientCc = recipientCc;
            return this;
        }

        /**
         * @Desc 密送人
         * @param recipientBcc
         * @param recipientsBcc
         * @return
         */
        public ExchangeClientBuilder recipientBcc(String recipientBcc, String... recipientsBcc) {
            // Prepare the list.
            List<String> 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<String> recipientBcc) {
            this.recipientBcc = recipientBcc;
            return this;
        }

        /**
         * @Desc 附件
         * @param attachment
         * @param attachments
         * @return
         */
        public ExchangeClientBuilder attachments(String attachment, String... attachments) {
            // Prepare the list.
            List<String> 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<String> 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<String, Object> 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<String, Object> 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("尊敬的客户:<BR>");
		builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您好!<BR>");
		builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		builder.append("您申请的电子发票已经开具,查看发票请点击附件,发票详情:<BR>");
		builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		builder.append("发票抬头:XX <BR>");
		builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		builder.append("发票号码:729020 <BR>");
		builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		builder.append("发票金额:45.00 <BR>");
		builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");  
		builder.append("&nbsp;&nbsp;&nbsp;");
		builder.append("2、23504480563  <BR>");
		builder.append("<BR><BR><BR><BR>");
		builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); 

		builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		builder.append("点击以下链接下载电子发票(PDF格式): <BR>");
		builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		builder.append("下载点在发票:");
		builder.append("<a href=\"http://2u35ou4t5it-5iy\">http://2u35ou4t5it-5iy</a>");

		ExchangeClient exchangeClient = new ExchangeClient.ExchangeClientBuilder()
				.hostname(HOSTNAME)
				.exchangeVersion(ExchangeVersion.Exchange2010)
				.username(USERNAME)
				.password(PASSWORD)
				.subject("电子发票通知")
				.message(builder.toString())
				.recipientTo(" ")
				.build();
		exchangeClient.sendExchange();
	}
}

 

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
Android Exchange 协议是一种用于在 Android 设备上发送和接收邮件的通信协议。它基于 Microsoft Exchange Server,并使用 Microsoft Exchange ActiveSync(EAS)进行通信。 Android Exchange 协议提供了以下功能和特点: 1. 邮件发送:Android Exchange 协议允许用户通过 Android 设备发送电子邮件。用户可以通过设备上的电子邮件应用程序编写邮件,选择收件人,并附加文件或图片。 2. 邮件同步:Android Exchange 协议通过与 Exchange Server 进行实时同步,确保所有邮件状态和操作在设备和服务器之间保持同步。这意味着,无论是通过设备还是服务器上的应用程序进行的操作,都会即时反映在另一端。 3. 日历和联系人同步:除了邮件,Android Exchange 协议还支持日历和联系人同步。用户可以在设备上查看和编辑 Exchange Server 上的日历事件和联系人信息,并确保更新会自动同步到服务器和其他设备上。 4. 安全性:Android Exchange 协议使用 Microsoft Exchange ActiveSync(EAS)进行通信,并支持加密和远程设备管理功能,以保护邮件的安全和用户的隐私。用户可以远程擦除设备上的数据,设置密码策略,并进行远程锁屏等操作。 综上所述, Android Exchange 协议为 Android 设备的用户提供了便捷的邮件发送和接收功能,并确保邮件、日历和联系人的同步和安全。无论是个人用户还是企业用户,都能从这一协议中受益,以更高效和安全的方式管理和处理电子邮件
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值