当前位置: 首页 > 工具软件 > EWS-Client > 使用案例 >

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

钱振
2023-12-01

引入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);
 类似资料: