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();
    }
}
相关推荐
佚先森3 分钟前
2024ARM网络验证 支持一键云注入引流弹窗注册机 一键脱壳APP加固搭建程序源码及教程
java·html
古月居GYH16 分钟前
在C++上实现反射用法
java·开发语言·c++
儿时可乖了1 小时前
使用 Java 操作 SQLite 数据库
java·数据库·sqlite
ruleslol1 小时前
java基础概念37:正则表达式2-爬虫
java
xmh-sxh-13141 小时前
jdk各个版本介绍
java
天天扭码2 小时前
五天SpringCloud计划——DAY2之单体架构和微服务架构的选择和转换原则
java·spring cloud·微服务·架构
程序猿进阶2 小时前
堆外内存泄露排查经历
java·jvm·后端·面试·性能优化·oom·内存泄露
FIN技术铺2 小时前
Spring Boot框架Starter组件整理
java·spring boot·后端