首页 > 编程语言 >java 通过 microsoft graph 调用outlook(三)

java 通过 microsoft graph 调用outlook(三)

时间:2024-05-23 17:08:23浏览次数:23  
标签:outlook java String graph return new import message public

这次会添加一个Reply接口,

并且使用6.10.0版本

 

直接上代码

一, POM

        <!--    office 365    -->
        <dependency>
            <groupId>com.microsoft.graph</groupId>
            <artifactId>microsoft-graph</artifactId>
            <version>6.10.0</version>
            <!--x-release-please-end-->
        </dependency>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-identity</artifactId>
            <version>1.11.0</version>
        </dependency>
        <!--    office 365    -->

 

二,Service / impl

主要讲一下Reply方法,Reply本质是添加评论,我们所有回复邮件,可以看到上下文时,实际都是添加了评论而已。(对比了outlook是一样的)

而Reply添加的附件,只有最后一份才会显示附件。

其他的附件,都只能在各自发送的邮件中找到,而Reply的连续回复中,只会有最后的附件。

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.models.*;
import com.microsoft.graph.serviceclient.GraphServiceClient;
import com.microsoft.graph.users.item.messages.item.reply.ReplyPostRequestBody;
import com.microsoft.graph.users.item.sendmail.SendMailPostRequestBody;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
 
import javax.annotation.PostConstruct;
import java.util.*;
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.scopes}")
    private String scopes;
 
    GraphServiceClient graphClient;
 
    /**
     * auth 授权
     */
    @PostConstruct
    public void auth() {
        ClientSecretCredential credential = new ClientSecretCredentialBuilder()
            .clientId(clientId)
            .tenantId(tenantId)
            .clientSecret(clientSecret)
            .build();
        graphClient = new GraphServiceClient(credential, scopes);
    }
 
 
    /**
     * 获取用户信息
     *
     * @param email 邮箱
     * @return
     */
    public User getUser(String email) {
        User user = graphClient
            .users()
            .byUserId(email)
            .get(requestConfiguration -> {
                requestConfiguration.queryParameters.select = new String[]{"displayName", "mail", "userPrincipalName"};
            });
        return user;
    }
 
    /**
     * 邮件文件夹
     *
     * @param email 邮箱
     * @return
     */
    @Override
    public MailFolderCollectionResponse getMailFolders(String email) {
        MailFolderCollectionResponse result = graphClient
            .users()
            .byUserId(email)
            .mailFolders()
            .get();
        return result;
    }
 
    /**
     * 获取文件夹邮件
     *
     * @param email 邮箱
     * @return
     */
    public MessageCollectionResponse getFolderMails(String email, String folderId, int page, int size) {
        MessageCollectionResponse message = graphClient
            .users()
            .byUserId(email)
            .mailFolders()
            .byMailFolderId(folderId)
            .messages()
            .get(requestConfiguration -> {
                requestConfiguration.queryParameters.select = new String[]{"id", "from", "isRead", "receivedDateTime", "subject"};
                requestConfiguration.queryParameters.skip = page * size;
                requestConfiguration.queryParameters.top = size;
                requestConfiguration.queryParameters.orderby = new String[]{"receivedDateTime DESC"};
            });
        return message;
    }
 
    /**
     * 获取邮件
     *
     * @param email 邮箱
     * @return
     */
    public MessageCollectionResponse getMails(String email, int page, int size) {
        MessageCollectionResponse message = graphClient
            .users()
            .byUserId(email)
            .messages()
            .get(requestConfiguration -> {
                requestConfiguration.queryParameters.select = new String[]{"id", "from", "isRead", "receivedDateTime", "subject"};
                requestConfiguration.queryParameters.skip = page * size;
                requestConfiguration.queryParameters.top = size;
                requestConfiguration.queryParameters.orderby = new String[]{"receivedDateTime DESC"};
            });
        return message;
    }
 
    /**
     * 邮件详情
     *
     * @param email     邮箱
     * @param messageId 邮件id
     * @return
     */
    @Override
    public Message getMailById(String email, String messageId) {
        Message message = graphClient
            .users()
            .byUserId(email)
            .messages()
            .byMessageId(messageId)
            .get(requestConfiguration -> {
                requestConfiguration.queryParameters.select = new String[]{"id", "from", "isRead", "receivedDateTime", "subject","body","hasAttachments"};
                requestConfiguration.queryParameters.expand = new String []{"attachments"};
            });
 
        //转换邮件中的图片
        message = getMailByIdWithAttachment(message);
        return message;
    }
 
    @Override
    public List<Message> getMailByIds(String email, List<String> messageIds) {
        List<Message> messages = new ArrayList<>();
        if (!CollectionUtils.isEmpty(messageIds)) {
            for (String messageId : messageIds) {
                Message message = getMailById(email, messageId);
                messages.add(message);
            }
        }
        return messages;
    }
 
    /**
     * 获取带有图片的邮件
     *
     * @param message 邮件
     * @return
     */
    @Override
    public Message getMailByIdWithAttachment(Message message) {
        //邮件内图片展示
        String emailBody = message.getBody().getContent();
        if(!CollectionUtils.isEmpty(message.getAttachments())) {
            for (Attachment attachment : message.getAttachments()) {
                if (attachment.getIsInline().booleanValue()) {
                    if ((attachment instanceof FileAttachment) && (attachment.getContentType().contains("image"))) {
                        FileAttachment fileAttachment = (FileAttachment) attachment;
                        byte[] contentBytes = fileAttachment.getContentBytes();
                        String imageContentIDToReplace = "cid:" + fileAttachment.getContentId();
                        emailBody = emailBody.replace(imageContentIDToReplace,
                            String.format("data:image;base64,%s", Base64.getEncoder().encodeToString(contentBytes
                            )));
                    }
 
                }
            }
        }
        message.getBody().setContent(emailBody);
        return message;
    }
 
    /**
     * 发送邮件
     *
     * @param sender    发件人
     * @param recipient 收件人
     * @param subject   主题
     * @param body      内容
     * @throws Exception
     */
    public Message sendMail(String sender, String recipient, String subject, String body) throws Exception {
        List<String> recipients = List.of(recipient);
        return sendMail(sender, recipients, subject, body, null);
    }
 
    /**
     * 发送邮件(多个收件人)
     *
     * @param sender     发件人
     * @param recipients 多收件人
     * @param subject    主题
     * @param body       内容
     * @throws Exception
     */
    public Message sendMail(String sender, List<String> recipients, String subject, String body) throws Exception {
        return sendMail(sender, recipients, subject, body, null);
    }
 
    @Override
    public Message sendMail(String sender, List<String> recipients, String subject, String body, List<FileAttachment> files) throws Exception {
        // Ensure client isn't null
        if (graphClient == null) {
            throw new Exception("Graph has not been initialized for user auth");
        }
        // Create a new message
        SendMailPostRequestBody sendMailPostRequestBody = new SendMailPostRequestBody();
        Message message = new Message();
        message.setSubject(subject);
        ItemBody itemBody=new ItemBody();
        itemBody.setContent(body);
        itemBody.setContentType(BodyType.Html);
        message.setBody(itemBody);
        //收件人
        if (!CollectionUtils.isEmpty(recipients)) {
            List<Recipient> toRecipients=new ArrayList<>();
            for (String item : recipients) {
                Recipient recipient = new Recipient();
                EmailAddress emailAddress = new EmailAddress();
                emailAddress.setAddress(item);
                recipient.setEmailAddress(emailAddress);
                toRecipients.add(recipient);
            }
            message.setToRecipients(toRecipients);
        }
        //附件
        message = addAttarchment(message, files);
        // Send the message
        sendMailPostRequestBody.setMessage(message);
        graphClient
            .users()
            .byUserId(sender)
            .sendMail()
            .post(sendMailPostRequestBody);
        return message;
    }
    public Message replyMail(String messageId, String sender, String recipient, String body) throws Exception {
        List<String> recipients = List.of(recipient);
        return replyMail(messageId, sender, recipients, body, null);
    }
    public Message replyMail(String messageId, String sender, List<String> recipients, String body) throws Exception {
        return replyMail(messageId, sender, recipients, body, null);
    }
    @Override
    public Message replyMail(String messageId, String sender, List<String> recipients, String body, List<FileAttachment> files) throws Exception {
        ReplyPostRequestBody replyPostRequestBody=new ReplyPostRequestBody();
        Message message = new Message();
        //附件
        message = addAttarchment(message, files);
        //收件人
        if (!CollectionUtils.isEmpty(recipients)) {
            List<Recipient> toRecipients=new ArrayList<>();
            for (String item : recipients) {
                Recipient recipient = new Recipient();
                EmailAddress emailAddress = new EmailAddress();
                emailAddress.setAddress(item);
                recipient.setEmailAddress(emailAddress);
                toRecipients.add(recipient);
            }
            message.setToRecipients(toRecipients);
        }
        replyPostRequestBody.setMessage(message);
        replyPostRequestBody.setComment(body);
        graphClient
            .users()
            .byUserId(sender)
            .messages()
            .byMessageId(messageId)
            .reply()
            .post(replyPostRequestBody);
        return message;
    }
    @Override
    public Message addAttarchment(Message message, List<FileAttachment> files) {
        if (files != null && files.size() > 0) {
            List<Attachment> attachmentList = new ArrayList<>();
            for (FileAttachment file : files) {
                FileAttachment attachment = new FileAttachment();
                attachment.setName(file.getName());
                attachment.setOdataType("#microsoft.graph.fileAttachment");
                attachment.setContentType(file.getContentType());
                attachment.setContentBytes(file.getContentBytes());
                attachment.setIsInline(file.getIsInline());
                attachment.setContentId(file.getContentId());
                attachmentList.add(attachment);
            }
            message.setAttachments(attachmentList);
        }
        return message;
    }
    @Override
    public Message setRead(String sender, Message message) {
        if (!message.getIsRead()) {
            Message newMessage = new Message();
            newMessage.setIsRead(true);
            graphClient
                .users()
                .byUserId(sender)
                .messages()
                .byMessageId(message.getId())
                .patch(newMessage);
        }
        return message;
    }
}

 

三, Controller

package com.xxx.mail.controller;
 
 
import com.xxx.common.core.domain.R;
import com.xxx.common.satoken.utils.LoginHelper;
import com.xxx.common.web.core.BaseController;
import com.xxx.mail.domain.MessageVo;
import com.xxx.mail.service.IMailOffice365Service;
import com.microsoft.graph.models.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
 
 
import java.util.List;
 
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/mail365")
public class MailController extends BaseController {
 
    @Autowired
    IMailOffice365Service mailOffice365Service;
 
    @GetMapping("/getUser")
    public R<User> getUser() {
        String account = LoginHelper.getLoginUser().getEmail();
        User user = mailOffice365Service.getUser(account);
        return R.ok(user);
    }
 
    @GetMapping("/getMailFolders")
    public R<List<MailFolder>> getMailFolders() {
        String account = LoginHelper.getLoginUser().getEmail();
        MailFolderCollectionResponse folder = mailOffice365Service.getMailFolders(account);
        return R.ok(folder.getValue());
    }
 
    @GetMapping("/getFolderMails")
    public R<List<Message>> getFolderMails(String folderId, int pageIndex) {
        String account = LoginHelper.getLoginUser().getEmail();
        MessageCollectionResponse mails = mailOffice365Service.getFolderMails(account, folderId, pageIndex, 10);
        return R.ok(mails.getValue());
    }
 
    @GetMapping("/getMails")
    public R<List<Message>> getMails(int pageIndex) {
        String account = LoginHelper.getLoginUser().getEmail();
        MessageCollectionResponse mails = mailOffice365Service.getMails(account, pageIndex, 10);
        return R.ok(mails.getValue());
    }
 
    @GetMapping("/getMailById")
    public R<Message> getMailById(String messageId) {
        String account = LoginHelper.getLoginUser().getEmail();
        Message mail = mailOffice365Service.getMailById(account, messageId);
        //设置已读
        mailOffice365Service.setRead(account,mail);
        return R.ok(mail);
    }
 
    @GetMapping("/getMailByIds")
    public R<List<Message>> getMailByIds(List<String> messageIds){
        String account = LoginHelper.getLoginUser().getEmail();
        List<Message> mails = mailOffice365Service.getMailByIds(account, messageIds);
        for(Message mail : mails){
            //设置已读
            mailOffice365Service.setRead(account,mail);
        }
        return R.ok(mails);
    }
 
    @PostMapping("/sendMail")
    public R<Message> sendMail(@RequestBody MessageVo req) throws Exception {
        String account = LoginHelper.getLoginUser().getEmail();
        mailOffice365Service.sendMail(
            account
            ,req.getRecipients()
            ,req.getSubject()
            ,req.getBody()
            ,req.getAttachments()
        );
        return R.ok();
    }
 
    @PostMapping("/replyMail")
    public R<Message> replyMail(@RequestBody MessageVo req) throws Exception {
        String account = LoginHelper.getLoginUser().getEmail();
        Message message = mailOffice365Service.replyMail(req.getMessageId()
            , account
            , req.getRecipients()
            , req.getBody()
            , req.getAttachments());
        return R.ok(message);
    }
 
}

MessageVo

这个类,纯粹是为了发送邮件时,带上附件一起调用接口。

package com.xxx.mail.domain;
 
import com.microsoft.graph.models.Attachment;
import com.microsoft.graph.models.FileAttachment;
import lombok.Data;
 
import java.util.ArrayList;
import java.util.List;
 
@Data
public class MessageVo {
    private String messageId;
    private List<String> recipients;
    private String subject;
    private String body;
    private List<FileAttachment> attachments=new ArrayList<>();
}

 

标签:outlook,java,String,graph,return,new,import,message,public
From: https://www.cnblogs.com/hanjun0612/p/18208976

相关文章

  • Pairwise实现(Java篇)
    importjava.util.HashMap;/***PairWise(成对)测试方法*author:likeqc*date:2021-4-411:06:59*/classPairWise{/***@paramstrString[][],二维数组,一维数组str[i]中存放第i个因素的因子*/privatestaticvoidsolution(String[][]s......
  • 位运算符在 Javascript 中的运用
    零、资料JavaScript中的位运算和权限设计javascript位运算技巧巧用JS位运算JavaScript位运算及其妙用聊聊JavaScript中的二进制数一、权限在权限设计时,每一个基础权限单元都是二进制数形式,有且只有一位值是1,其余全部是0,即权限码是 2^n 。所以,在这套设......
  • 关于如何使用JNI将C语言接口打包成可供java环境调用的so库文件
    一、环境检查在linux下打包.so文件,首先需要确认是否有安装java环境,可通过在终端中输入指令java的方式来进行查看。如下图所示,则为已安装java环境。  若当前未安装java环境,则可通过在终端中输入如下指令进行安装,我这里使用的java环境为1.8.0版本。sudoapt-getinstallo......
  • 使用-HTML5-和-JavaScript-开发-Windows-商店应用-全-
    使用HTML5和JavaScript开发Windows商店应用(全)原文:zh.annas-archive.org/md5/8F13EC8AC7BDB8535E7218C5DDB48475译者:飞龙协议:CCBY-NC-SA4.0序言使用HTML5和JavaScript开发WindowsStore应用是一本实践性强的指南,涵盖了WindowsStore应用的基本重要特性以及......
  • 精通-JavaScript-高性能-全-
    精通JavaScript高性能(全)原文:zh.annas-archive.org/md5/582AFDEF15013377BB79AB8CEA3B2B47译者:飞龙协议:CCBY-NC-SA4.0序言欢迎来到精通JavaScript高性能。在这本书中,我们已经以帮助任何JavaScript开发者,无论他们是新手上路还是经验丰富的老手的方式,覆盖了JavaScrip......
  • Java的深浅拷贝认识
    目录浅拷贝深拷贝分辨代码里的深浅拷贝在Java中,深拷贝和浅拷贝是对象复制的两种方式,主要区别在于对对象内部的引用类型的处理上。浅拷贝定义:浅拷贝是指创建一个新的对象,但这个新对象的属性(包括引用类型的属性)仍然指向原来对象的属性。换言之,如果原对象中的属性是一个引用类型......
  • #Java集合的组内平均值的计算方法
    要计算Java集合(例如List或Set中的Integer、Double或其他数值类型的对象)的组内平均值,我们需要遍历这个集合,累加所有的元素值,然后除以集合的大小(即元素的数量)。以下是一个详细的步骤说明和完整的代码示例。1.步骤说明(1)创建集合:首先,我们需要一个包含数值的集合。在这个例子中,我们将......
  • Java静态变量在静态方法内部无法改变值
    一、如何解决“Java静态变量在静态方法内部无法改变值”的问题在Java中,静态变量(也称为类变量)属于类本身,而不是类的任何特定实例。它们可以在没有创建类的实例的情况下访问和修改。如果我们发现在静态方法内部无法改变静态变量的值,这通常是因为我们的代码中有一些逻辑错误或误解。......
  • 二分图的判定(Bipartite graph pending)
    二分图的判定(Bipartitegraphpending)////CreatedbyLANSGANBSon24-5-23.///**codetemplate:https://github.com/LANSGANBS/code-template*local:C:\Users\18019\CLionProjects\.cpp-code*URL:NULL*Last_Status:NULL*写完这道就去原*/#include<b......
  • JAVA面试题
    第一章-Java基础篇1、你是怎样理解OOP面向对象难度系数:⭐2、重载与重写区别难度系数:⭐3、接口与抽象类的区别难度系数:⭐4、深拷贝与浅拷贝的理解难度系数:⭐5、sleep和wait区别难度系数:⭐6、什么是自动拆装箱int和Integer有什么区别难度系数:⭐7、......