java 通过 microsoft graph 调用outlook(二)

这次提供一些基础调用方式API

一 POM文件

        <!--    office 365    -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>32.1.3-jre</version>
        </dependency>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-identity</artifactId>
            <version>1.11.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.microsoft.graph</groupId>
            <artifactId>microsoft-graph</artifactId>
            <version>5.77.0</version>
        </dependency>
        <!--    office 365    -->

二 Service / Impl

service

package com.xxx.mail.service;

import com.microsoft.graph.models.Message;
import com.microsoft.graph.models.User;
import com.microsoft.graph.requests.MessageCollectionPage;

import java.util.List;

public interface IMailOffice365Service {
    User getUser(String email);

    MessageCollectionPage getMails(String email,int page,int size);

    Message getMailById(String email, String messageId);

    Message getMailByIdWithAttachment(Message message);

    void sendMail(String Sender , String recipient , String subject, String body) throws Exception;

    void sendMail(String Sender ,List<String> recipients ,String subject, String body) throws Exception;
}

impl

package com.xxx.mail.service.impl;

import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.xxx.mail.service.IMailOffice365Service;
import com.microsoft.graph.authentication.IAuthenticationProvider;
import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
import com.microsoft.graph.models.*;
import com.microsoft.graph.requests.GraphServiceClient;
import com.microsoft.graph.requests.MessageCollectionPage;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

@Service("mailOffice365Util")
public class MailOffice365Impl implements IMailOffice365Service {

    @Value("${mailOffice365.clientId}")
    private String clientId;
    @Value("${mailOffice365.tenantId}")
    private String tenantId;
    @Value("${mailOffice365.clientSecret}")
    private String clientSecret;
    @Value("${mailOffice365.graphUserScopes}")
    private String graphUserScopes;

    private IAuthenticationProvider authProvider;

    @PostConstruct
    public void init(){
        auth();
    }

    /**
     * auth 授权
     */
    private void auth(){
        ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
            .clientId(clientId)
            .tenantId(tenantId)
            .clientSecret(clientSecret)
            .build();
        authProvider = new TokenCredentialAuthProvider(
            Arrays.asList("https://graph.microsoft.com/.default")
            , clientSecretCredential
        );
    }

    /**
     * 获取用户信息
     * @param email
     * @return
     */
    public User getUser(String email) {
        GraphServiceClient<Request> graphClient = GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();
        User user=graphClient.users(email)
            .buildRequest()
            .select("displayName,mail,userPrincipalName")
            .get();
        return user;
    }

    /**
     * 获取邮件
     * @param email
     * @return
     */
    public MessageCollectionPage getMails(String email,int page,int size) {
        GraphServiceClient<Request> graphClient = GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();
        MessageCollectionPage message = graphClient.users(email)
//            .mailFolders("inbox")
            .messages()
            .buildRequest()
            .select("id,from,isRead,receivedDateTime,subject")
            .skip(page*size)
            .top(size)
            .orderBy("receivedDateTime DESC")
            .get();
        return message;
    }

    @Override
    public Message getMailById(String email, String messageId) {
        GraphServiceClient<Request> graphClient = GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();
        Message message = graphClient.users(email)
//            .mailFolders("inbox")
            .messages()
            .byId(messageId)
            .buildRequest()
            .select("id,from,body")
            .expand("attachments")
            .get();
        return message;
    }

    /**
     * 获取带有图片的邮件
     * @param message
     * @return
     */
    @Override
    public Message getMailByIdWithAttachment(Message message) {
        //图片展示
        String emailBody = message.body.content;
        for (Attachment attachment : message.attachments.getCurrentPage())
        {
            if (attachment.isInline.booleanValue())
            {
                if ((attachment instanceof FileAttachment) &&(attachment.contentType.contains("image")))
                {
                    FileAttachment fileAttachment = (FileAttachment)attachment;
                    byte[] contentBytes = fileAttachment.contentBytes;
                    String imageContentIDToReplace = "cid:" + fileAttachment.contentId;
                    emailBody = emailBody.replace(imageContentIDToReplace,
                        String.format("data:image;base64,%s", Base64.getEncoder().encodeToString(contentBytes
                        )));
                }

            }
        }
        message.body.content=emailBody;
        return message;
    }

    /**
     * 发送邮件
     * @param sender
     * @param recipient
     * @param subject
     * @param body
     * @throws Exception
     */
    public void sendMail(String sender ,String recipient ,String subject, String body) throws Exception {
        List<String> recipients=List.of(recipient);
        sendMail(sender,recipients,subject,body);
    }

    /**
     * 发送邮件(多个收件人)
     * @param sender
     * @param recipients
     * @param subject
     * @param body
     * @throws Exception
     */
    public void sendMail(String sender ,List<String> recipients ,String subject, String body) throws Exception {
        GraphServiceClient<Request> graphClient = GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();
        // Ensure client isn't null
        if (graphClient == null) {
            throw new Exception("Graph has not been initialized for user auth");
        }

        // Create a new message
        final Message message = new Message();
        message.subject = subject;
        message.body = new ItemBody();
        message.body.content = body;
        message.body.contentType = BodyType.TEXT;

        if(recipients!=null && recipients.size()>0) {
            message.toRecipients=new ArrayList<>();
            recipients.forEach(x->{
                final Recipient toRecipient = new Recipient();
                toRecipient.emailAddress = new EmailAddress();
                toRecipient.emailAddress.address = x;
                message.toRecipients.add(toRecipient);
            });
        }

        // Send the message
        graphClient
            .users(sender)
            .sendMail(UserSendMailParameterSet.newBuilder()
                .withMessage(message)
                .build())
            .buildRequest()
            .post();

    }

}

三 调用

读取邮箱的权限,在第一篇中有说,不赘述了。

package com.xxx.mail.controller;


import com.xxx.common.core.domain.R;
import com.xxx.mail.service.IMailOffice365Service;
import com.microsoft.graph.models.Message;
import com.microsoft.graph.models.User;
import com.microsoft.graph.requests.MessageCollectionPage;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/mail")
public class TestController {

    @Autowired
    IMailOffice365Service mailOffice365Service;

    @GetMapping("/getUser")
    public R<User> getUser() {
        User user=mailOffice365Service.getUser("发送者邮箱");
        return R.ok(user);
    }

    @GetMapping("/getMails")
    public R<MessageCollectionPage> getMails() {
        MessageCollectionPage mails=mailOffice365Service.getMails("发送者邮箱",0,10);
        return R.ok(mails);
    }

    @GetMapping("/getMailById")
    public R<Message> getMailById(String messageId) {
        Message mail=mailOffice365Service.getMailById("发送者邮箱",messageId);
        //转换邮件中的图片
        mail=mailOffice365Service.getMailByIdWithAttachment(mail);
        return R.ok(mail);
    }

    @PostMapping("/sendMail")
    public R<Void> sendMail(String messageId) throws Exception {
        String Sender="发送者邮箱";
        String recipient="接收者邮箱" ;
        String subject="测试邮件";
        String body="这是一封测试邮件";
        mailOffice365Service.sendMail(Sender,recipient,subject,body);
        return R.ok();
    }
}
相关推荐
秋意钟4 分钟前
Spring新版本
java·后端·spring
椰椰椰耶6 分钟前
【文档搜索引擎】缓冲区优化和索引模块小结
java·spring·搜索引擎
mubeibeinv7 分钟前
项目搭建+图片(添加+图片)
java·服务器·前端
青莳吖9 分钟前
Java通过Map实现与SQL中的group by相同的逻辑
java·开发语言·sql
Buleall16 分钟前
期末考学C
java·开发语言
重生之绝世牛码18 分钟前
Java设计模式 —— 【结构型模式】外观模式详解
java·大数据·开发语言·设计模式·设计原则·外观模式
小蜗牛慢慢爬行24 分钟前
有关异步场景的 10 大 Spring Boot 面试问题
java·开发语言·网络·spring boot·后端·spring·面试
新手小袁_J1 小时前
JDK11下载安装和配置超详细过程
java·spring cloud·jdk·maven·mybatis·jdk11
呆呆小雅1 小时前
C#关键字volatile
java·redis·c#
Monly211 小时前
Java(若依):修改Tomcat的版本
java·开发语言·tomcat