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();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章