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();
    }
}
相关推荐
激流丶5 分钟前
【Kafka 实战】如何解决Kafka Topic数量过多带来的性能问题?
java·大数据·kafka·topic
Themberfue8 分钟前
Java多线程详解⑤(全程干货!!!)线程安全问题 || 锁 || synchronized
java·开发语言·线程·多线程·synchronized·
让学习成为一种生活方式25 分钟前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
晨曦_子画31 分钟前
编程语言之战:AI 之后的 Kotlin 与 Java
android·java·开发语言·人工智能·kotlin
南宫生1 小时前
贪心算法习题其三【力扣】【算法学习day.20】
java·数据结构·学习·算法·leetcode·贪心算法
Heavydrink1 小时前
HTTP动词与状态码
java
ktkiko111 小时前
Java中的远程方法调用——RPC详解
java·开发语言·rpc
计算机-秋大田1 小时前
基于Spring Boot的船舶监造系统的设计与实现,LW+源码+讲解
java·论文阅读·spring boot·后端·vue
神里大人1 小时前
idea、pycharm等软件的文件名红色怎么变绿色
java·pycharm·intellij-idea
小冉在学习2 小时前
day53 图论章节刷题Part05(并查集理论基础、寻找存在的路径)
java·算法·图论