这次提供一些基础调用方式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();
}
}