ews java + Oauth2实现office 365发送邮件

引入maven包:

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

使用office 365邮箱服务收发邮件有两种校验方式,一种是老的basic authentication, 这种方式目前已不建议使用,如下使用的是userName, password进行验证的方式。

public static boolean sendExchange(MailConfig mailInfo) {
// The Exchange Server Version.

    try (ExchangeService exchangeService = new ExchangeService(exchangeVersion)) {
        
    	// Credentials to sign in the MS Exchange Server.
        ExchangeCredentials exchangeCredentials = new WebCredentials(ExchangeMailUtil.getUsername(), ExchangeMailUtil.getPassword());
        exchangeService.setCredentials(exchangeCredentials);
        
        // URL of exchange web service for the mailbox.
        exchangeService.setUrl(new URI("https://outlook.office365.com/ews/exchange.asmx"));
        // The email.
        EmailMessage emailMessage;
        emailMessage = new EmailMessage(exchangeService);
        emailMessage.setSubject(mailInfo.getSubject());
        MessageBody body = MessageBody.getMessageBodyFromText(mailInfo.getContent());
        body.setBodyType(BodyType.HTML);
        emailMessage.setBody(body);

        // TO recipient.
        String[] recipients = mailInfo.getToAddresses().split(",");
        for (String recipient : recipients) {
            emailMessage.getToRecipients().add(recipient);
        }

        // CC recipient.
        if (StringUtils.isNotBlank(mailInfo.getCcAddresses())) {
            for (String recipient : mailInfo.getCcAddresses().split(",")) {
                emailMessage.getCcRecipients().add(recipient);
            }
        }

        // Attachements.
        if (mailInfo.getAttachFileNames() != null && mailInfo.getAttachFileNames().length > 0) {
            for (String attachmentPath : mailInfo.getAttachFileNames()) {
                getLocalFile(attachmentPath);
                emailMessage.getAttachments().addFileAttachment(attachmentPath);
            }
        }

        emailMessage.send();
    } catch (Exception ex) {
        log.info("An exception occured while sending an email.", ex);
        ex.printStackTrace();
        return false;
    }
    return true;
}

最新推荐是使用Oauth令牌验证access,进行邮箱服务,可参考官网https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth
分三步走,
第一步注册应用,获得client_id, tenant_id 和client_secret.
第二步,获取token.
private static String getOauthTokenBase64() {
String tenant_id = “your tenant ID”;
String client_id = “your client ID”;
String client_secret = “your client secret”;
String scope = “https://outlook.office365.com/.default”;

	  String url = "https://login.microsoftonline.com/" + tenant_id + "/oauth2/v2.0/token";
	  HttpClient httpClient = new HttpClient();
	  PostMethod postMethod = new PostMethod(url);
	  postMethod.addRequestHeader("accept", "*/*");
	  postMethod.addRequestHeader("connection", "Keep-Alive");
	  postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=GBK");
	  //必须设置下面这个Header
	  postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
	  //添加请求参数
	  postMethod.addParameter("grant_type", "client_credentials");
	  postMethod.addParameter("client_id", client_id);
	  postMethod.addParameter("client_secret", client_secret);
	  postMethod.addParameter("scope", scope);
	  String tooooken = "";
	  try {
	    int code = httpClient.executeMethod(postMethod);
	    String resBody = postMethod.getResponseBodyAsString();
	    if (code == 200) {
	      Map<String, String> map = JSON.parseObject(resBody, Map.class);
	      tooooken = map.get("access_token");
	    } else {
	      log.error("get token from office 365 faile, response {}",resBody);
	    }
	  } catch (IOException e) {
	    log.error(e.getMessage());
	    e.printStackTrace();
	  } catch (HttpException e) {
		e.printStackTrace();
	} catch (java.io.IOException e) {
		e.printStackTrace();
	} finally {
	    postMethod.releaseConnection();
	  }
	  return tooooken;
}
第三部,将token带入ews请求头
 // Credentials to sign in the MS Exchange Server.
        exchangeService.setImpersonatedUserId(new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "test@163.com"));
        exchangeService.getHttpHeaders().put("Authorization", "Bearer " + access_token);
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java EWS订阅是通过使用EWS Java API实现的。您可以使用EWS Java API中的Pull Notifications来进行订阅。在订阅过程中,您可以选择订阅每个邮箱或者特定的文件夹。您可以选择使用流、请求或推送通知,并选择接收哪种类型的事件,例如新邮件、创建、删除、修改日期等等。一旦订阅创建成功,EWS事件将以异步方式从邮箱服务器发送到客户端。\[2\] 如果您需要从HTML中提取body信息,您可以使用一个工具类来实现。下面是一个示例的工具类,可以从HTML中提取内容: ```java public class DataUtils { public static String getContentFromHtml(String content){ content = content.replaceAll("</?\[^>\]+>", ""); //剔出<html>的标签 content = content.replaceAll("<a>\\s*|\t|\r|\n</a>", ""); content = content.replaceAll(" ", ""); content = content.replaceAll("\n", ""); return content; } } ``` 您可以使用这个工具类中的`getContentFromHtml`方法来提取HTML中的body信息。\[3\] #### 引用[.reference_title] - *1* *3* [EWS Java API 的基本使用](https://blog.csdn.net/m0_37972348/article/details/83960690)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [EWS 通过SubscribeToPullNotifications订阅Exchange新邮件提醒](https://blog.csdn.net/weixin_33738578/article/details/93244544)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值