如何用Java和Maven实现Microsoft Graph API邮件发送功能
Absolutely! I’ve got you covered with a full Maven-compatible Java implementation that handles both acquiring an access token from Microsoft Graph and sending emails using that token. Since you’ve already validated the flow in Postman, this should map directly to your existing setup.
Step 1: Add Maven Dependencies
First, update your pom.xml with the required dependencies for authentication (MSAL4J) and Microsoft Graph API interactions:
<dependencies> <!-- Microsoft Graph Core Library --> <dependency> <groupId>com.microsoft.graph</groupId> <artifactId>microsoft-graph</artifactId> <version>6.3.0</version> <!-- Use the latest stable version --> </dependency> <!-- MSAL4J for authentication --> <dependency> <groupId>com.microsoft.azure</groupId> <artifactId>msal4j</artifactId> <version>1.24.0</version> <!-- Latest stable version --> </dependency> <!-- For JSON processing (if needed) --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency> </dependencies>
Step 2: Configure Azure AD App Details
You’ll need the credentials from your Azure AD app registration (the same ones you used in Postman). Store these in a config class or properties file for security:
public class GraphConfig { // Replace these with your actual values public static final String TENANT_ID = "your-tenant-id"; public static final String CLIENT_ID = "your-client-id"; public static final String CLIENT_SECRET = "your-client-secret"; public static final String GRAPH_SCOPE = "https://graph.microsoft.com/.default"; public static final String GRAPH_TOKEN_ENDPOINT = "https://login.microsoftonline.com/" + TENANT_ID + "/oauth2/v2.0/token"; }
Step 3: Acquire Access Token
Use MSAL4J to fetch a client credentials flow token (this matches the client credential flow you likely used in Postman):
import com.microsoft.aad.msal4j.ClientCredentialFactory; import com.microsoft.aad.msal4j.ClientCredentialParameters; import com.microsoft.aad.msal4j.ConfidentialClientApplication; import com.microsoft.aad.msal4j.IAuthenticationResult; import java.util.Collections; import java.util.concurrent.CompletableFuture; public class GraphTokenProvider { public static String getAccessToken() throws Exception { // Initialize confidential client application ConfidentialClientApplication app = ConfidentialClientApplication.builder( GraphConfig.CLIENT_ID, ClientCredentialFactory.createFromSecret(GraphConfig.CLIENT_SECRET)) .authority(GraphConfig.GRAPH_TOKEN_ENDPOINT) .build(); // Set up token request parameters ClientCredentialParameters parameters = ClientCredentialParameters.builder( Collections.singleton(GraphConfig.GRAPH_SCOPE)) .build(); // Fetch token asynchronously CompletableFuture<IAuthenticationResult> future = app.acquireToken(parameters); IAuthenticationResult result = future.get(); return result.accessToken(); } }
Step 4: Send Email with Microsoft Graph
Once you have the access token, use the Microsoft Graph SDK to construct and send an email:
import com.microsoft.graph.models.*; import com.microsoft.graph.requests.GraphServiceClient; import okhttp3.OkHttpClient; import okhttp3.Request; import java.util.Collections; import java.util.concurrent.CompletableFuture; public class GraphEmailSender { public static void sendEmail(String accessToken) { // Create an authenticated Graph client GraphServiceClient<Request> graphClient = GraphServiceClient.builder() .authenticationProvider(request -> { request.addHeader("Authorization", "Bearer " + accessToken); return CompletableFuture.completedFuture(null); }) .httpClient(new OkHttpClient()) .buildClient(); // Construct the email message Message message = new Message(); message.subject = "Test Email from Java Maven App"; ItemBody body = new ItemBody(); body.contentType = BodyType.TEXT; body.content = "Hello, this is a test email sent via Microsoft Graph API using Java and Maven!"; message.body = body; // Set recipients Recipient toRecipient = new Recipient(); EmailAddress emailAddress = new EmailAddress(); emailAddress.address = "recipient@example.com"; toRecipient.emailAddress = emailAddress; message.toRecipients = Collections.singletonList(toRecipient); // Send the email try { graphClient.me() .sendMail(message, false) .buildRequest() .post(); System.out.println("Email sent successfully!"); } catch (Exception e) { System.err.println("Error sending email: " + e.getMessage()); e.printStackTrace(); } } public static void main(String[] args) { try { String accessToken = GraphTokenProvider.getAccessToken(); sendEmail(accessToken); } catch (Exception e) { e.printStackTrace(); } } }
Key Notes to Remember
- Permissions: Ensure your Azure AD app has the
Mail.Sendpermission (either delegated or application-level, depending on your flow). If using application permissions, you’ll need to grant admin consent. - Flow Variation: If you used the authorization code flow in Postman (instead of client credentials), you can adjust the token acquisition code to use MSAL4J’s authorization code flow implementation instead.
- Versioning: Always use the latest stable versions of the Microsoft Graph and MSAL4J dependencies to avoid compatibility issues.
内容的提问来源于stack exchange,提问作者E_FreeLancer




