Microsoft - RestTemplate

API 地址:

https://docs.microsoft.com/zh-cn/graph/api/user-list?view=graph-rest-1.0&tabs=http

一. 启动类添加RestTemplate

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

二. 添加Maven依赖

// SpringBoot版本:2.4.1(其他版本并未测试,该方法只是使用了包中的实体类)
<!--Exchange Online-->
<dependency>
    <groupId>com.microsoft.graph</groupId>
    <artifactId>microsoft-graph</artifactId>
    <version>3.0.0</version>
</dependency>

三. 注入RestTemplate、TemplateEngine

@Resource
RestTemplate restTemplate;
@Resource
TemplateEngine templateEngine;

四. 新建实体类

1. 获取token使用的实体类

@Data
public class TokenDo {
    private String token_type;
    private Integer expires_in;
    private Integer ext_expires_in;
    // 凭证
    private String access_token;
}

2. 回复邮件使用的实体(构建body参数)

@Data
public class RequestDO {
    // 构建收件人
    private Message message;
    // 消息体
    private String comment;
}

五. RestTemplate 实操(案例中使用的多数实体类均为com.microsoft.graph包下实体)

1. 获取客户端凭证:token

public String getToken() {
    String url = "https://login.chinacloudapi.cn/租户id/oauth2/v2.0/token";
    MultiValueMap map = new LinkedMultiValueMap();
    map.add("grant_type", AzureConstants.GRANT_TYPE);
    map.add("client_id", AzureConstants.CLIENT_ID);
    map.add("client_secret", AzureConstants.CLIENT_SECRET);
    map.add("scope", AzureConstants.SCOPE);

    ResponseEntity<TokenDo> responseEntity = restTemplate.postForEntity(url, map, TokenDo.class);
    System.out.println("token --->" + responseEntity.getBody().getAccess_token());
    return responseEntity.getBody().getAccess_token();
}

2. 获取用户列表

public Object getUserList() {
    String url = "https://microsoftgraph.chinacloudapi.cn/v1.0/users";
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", getToken());
    ResponseEntity<HashMap> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<String>(headers), HashMap.class);
    ArrayList<User> userArrayList = (ArrayList<User>) response.getBody().get("value");
    return userArrayList;
}

3. 获取用户邮件列表

public Object getUserMailList() {
    String url = "https://microsoftgraph.chinacloudapi.cn/v1.0/users('用户邮箱')/messages";
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", getToken());
    ResponseEntity<HashMap> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<String>(headers), HashMap.class);
    response.getBody().get("@odata.nextLink");//下一页的请求地址
    return response.getBody();
}

4. 获取邮件

public Object getMail() {
    String url = "https://microsoftgraph.chinacloudapi.cn/v1.0/users('用户邮箱')/messages/邮件id";

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", getToken());
    ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<String>(headers), Object.class);
    return response.getBody();
}

5. 回复纯文本邮件

// 注意1:设置邮件的收件人经测试可以不传,也可以返回到该邮件原始的发件人(目标收件人)、
// 注意2:回复消息体正文可以是纯文本,也可以是HTML格式的字符串
public Object replyMail() {
    /* 1. 构建链接 */
    String url = "https://microsoftgraph.chinacloudapi.cn/v1.0/users('用户邮箱')/messages/邮箱id/reply";

    /* 2. 构建收件人集合 */
    Message message = new Message();
    LinkedList<Recipient> toRecipientsList = new LinkedList<Recipient>();
    Recipient toRecipients = new Recipient();
    EmailAddress emailAddress = new EmailAddress();
    emailAddress.address = "1334390020@qq.com";
    emailAddress.name = "Zhang";
    toRecipients.emailAddress = emailAddress;
    toRecipientsList.add(toRecipients);
    message.toRecipients = toRecipientsList;

    /* 3. 构建消息体模板 */
    Context context = new Context();
    context.setVariable("content","单纯的回复一下怎么了?");
    String mail = templateEngine.process("mailtemplate.html",context);

    /* 4. 构建请求参数 */
    RequestDO requestDO = new RequestDO();
    requestDO.setComment(mail);
    requestDO.setMessage(message);
    String s = JSON.toJSONString(requestDO);

    /* 5. 构建请求头和请求体 */
    RequestEntity<String> requestEntity = RequestEntity.post(url)
                .accept(MediaType.APPLICATION_JSON)
                .header("Content-Type", "application/json")
                .header("Authorization",getToken())
                .body(s);

    ResponseEntity<Object> exchange = restTemplate.exchange(requestEntity, Object.class);
    return exchange;
}

6. 国际版拉取常量类

package com.vevor.crm.constants;

/**
 * @author :zhangbocong
 * @version :V1.0
 * @program :spring_boot_demo
 * @date :Created in  19:04
 * @description :
 */
public class AzureConstant {
    /**
     * 增量拉取用户邮件URL(国际版)
     */
    public static final String MAIL_ALL_URL = "https://graph.microsoft.com/v1.0/users('%s')/mailFolders/%s/messages/delta";

    /**
     * 增量邮件请求参数名称
     */
    public static final String DELTA_LINK = "@odata.deltaLink";

    /**
     * 下一页邮件请求参数名称
     */
    public static final String NEXT_LINK = "@odata.nextLink";

    /**
     * 邮件请求集合参数名称
     */
    public static final String MAIL_VALUES = "value";
}

7. 增量拉取用户邮件列表 :国际版

// url 拉取邮件URL
public Map<String, Object> getDeltaMailByUrl(String url) {
    /* 1. 参数非空验证 */
    if (StringUtils.isEmpty(url)) {
        throw new QueryException(CLI_ERR_VALIDATE_ERROR,
                String.format(CLI_ERR_VALIDATE_ERROR.getChnMsg(), "url"),
                CLI_ERR_VALIDATE_ERROR.getEngMsg());
    }

    /* 2. 获取用户全部邮件 */
    List<Message> messages = new ArrayList<>();
    // 2.1 初始化循环表示
    boolean nextPage = true;
    // 2.2 设置请求headers
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", getToken());
    headers.add("Prefer", "odata.maxpagesize="+pageSize);
    // 2.3 初始化返回值集合
    Map<String, Object> returnMap = new HashMap<>();

    /* 3. 开始轮询本次请求 */
    while (nextPage) {
    // 3.1 发起请求
    ResponseEntity<HashMap> response = null;
    try {
        response = restTemplate.exchange(url, HttpMethod.GET,
                                        new HttpEntity<String>(headers), HashMap.class);
    }catch (Exception e){
        throw new QueryException(CLI_ERR_MAIL_URL,
                        String.format(CLI_ERR_MAIL_URL.getChnMsg(), url),
                        CLI_ERR_MAIL_URL.getEngMsg());
        }
        // 3.2 获取本次请求邮件集合
        List values = (List) response.getBody().get(AzureConstant.MAIL_VALUES);
        // 3.3 如果values为空,表示已请求到最后一页,则不进行循环查询,并保存下次轮询时的增量URL
        if (values == null || values.size() <= 0) {
            // 3.4 关闭下次循环
            nextPage = false;
            // 3.5 获取下次增量轮询请求的URL
            returnMap.put("deltaLink",response.getBody().get(AzureConstant.DELTA_LINK));
        } else {
            // 3.4 设置下页邮件的URL
            url = response.getBody().get(AzureConstant.NEXT_LINK).toString();
            messages.addAll(values);
        }
    }
    returnMap.put("messages", messages);
    return returnMap;
}

8. 全量拉取用户邮件列表 :国际版

// mail 卖家邮箱, folderId 文件夹ID
public Map<String, Object> getUserMailAll(String mail, String folderId) {
    /* 1. 验证参数 */
    if (StringUtils.isEmpty(mail)) {
        throw new QueryException(CLI_ERR_VALIDATE_ERROR,
                String.format(CLI_ERR_VALIDATE_ERROR.getChnMsg(), "mail"),
                CLI_ERR_VALIDATE_ERROR.getEngMsg());
    }
    if (StringUtils.isEmpty(folderId)) {
        throw new QueryException(CLI_ERR_VALIDATE_ERROR,
                String.format(CLI_ERR_VALIDATE_ERROR.getChnMsg(), "folderId"),
                CLI_ERR_VALIDATE_ERROR.getEngMsg());
    }
    /* 2. 设置请求URL */
    String url = String.format(AzureConstant.MAIL_ALL_URL,mail,folderId);

    return getDeltaMailByUrl(url);
}