How to check file attachment status using MS Graph Api Send mail Java-SDK V5

B Jayachithra 51 Reputation points
2025-04-25T15:33:34.86+00:00

Hello Team,

We would like to check if file has been attached to mail or not using below code-MS Graph Api Java-Client credential flow.

attachmentsList1.add(fat);

AttachmentCollectionResponse attachmentCollectionResponse = new AttachmentCollectionResponse();

attachmentCollectionResponse.value = attachmentsList1;

AttachmentCollectionPage attachmentCollectionPage = new AttachmentCollectionPage(attachmentCollectionResponse, null);

message.attachments = attachmentCollectionPage;

Any other way to check file attachment status using graph api java?

Microsoft Security | Microsoft Entra | Microsoft Entra ID
{count} votes

Accepted answer
  1. SrideviM 5,710 Reputation points Microsoft External Staff Moderator
    2025-04-27T08:02:57.6333333+00:00

    Hello B Jayachithra,

    I understand you are trying to check if a file attachment is present when sending an email using Microsoft Graph Java SDK v5.

    To check if the file is attached before sending, you can validate like this:

    if (message.attachments != null &&
        message.attachments.getCurrentPage() != null &&
        message.attachments.getCurrentPage().size() > 0) {
        System.out.println("Attachment is present before sending.");
    } else {
        System.out.println("No attachment found before sending.");
    }
    

    After sending the email, you can verify the attachment status by checking the latest email in the Sent Items folder:

    var  sentMessagesPage  = graphClient.users(senderUserId)
        .mailFolders("sentitems")
        .messages()
        .buildRequest()
        .top(1)
        .orderBy("receivedDateTime desc")
        .select("subject,hasAttachments,receivedDateTime")
        .get(); 
    
    if (sentMessagesPage.getCurrentPage() != null &&
        !sentMessagesPage.getCurrentPage().isEmpty()) { 
    	Message  latestSentMessage  = sentMessagesPage.getCurrentPage().get(0); 
        if (Boolean.TRUE.equals(latestSentMessage.hasAttachments)) {
            System.out.println("Confirmed: Sent mail has attachments.");
        } else {
            System.out.println("Confirmed: Sent mail has no attachments.");
        }
    }
    

    Here is a full working example for your reference.
    (The attachment part is commented, so you can test with or without adding an attachment.)

    AuthProvider.java:

    package com.example.azureauth;
    
    import com.microsoft.graph.authentication.IAuthenticationProvider;
    import com.azure.identity.ClientSecretCredential;
    import com.azure.identity.ClientSecretCredentialBuilder;
    import java.net.URL;
    import java.util.concurrent.CompletableFuture;
    
    public class AuthProvider implements IAuthenticationProvider {
    
        private final ClientSecretCredential credential;
        private final String scope = "https://graph.microsoft.com/.default";
    
        public AuthProvider(String clientId, String clientSecret, String tenantId) {
            this.credential = new ClientSecretCredentialBuilder()
                    .clientId(clientId)
                    .clientSecret(clientSecret)
                    .tenantId(tenantId)
                    .build();
        }
    
        @Override
        public CompletableFuture<String> getAuthorizationTokenAsync(URL requestUrl) {
            return credential.getToken(
                            new com.azure.core.credential.TokenRequestContext()
                                    .addScopes(scope))
                    .toFuture()
                    .thenApply(accessToken -> accessToken.getToken());
        }
    }
    

    Main.java:

    package com.example.azureauth;
    
    import com.microsoft.graph.models.*;
    import com.microsoft.graph.requests.AttachmentCollectionPage;
    import com.microsoft.graph.requests.AttachmentCollectionResponse;
    import com.microsoft.graph.requests.GraphServiceClient;
    import okhttp3.Request;
    import java.nio.charset.StandardCharsets;
    import java.util.LinkedList;
    
    public class Main {
    
        public static void main(String[] args) {
    
            final String clientId = "appId";
            final String clientSecret = "secret_value";
            final String tenantId = "tenantId";
            final String senderUserId = "******@xxxxxx.onmicrosoft.com";
            final String recipientEmail = "******@xxxxxx.onmicrosoft.com";
    
            GraphServiceClient<Request> graphClient = GraphServiceClient
                    .builder()
                    .authenticationProvider(new AuthProvider(clientId, clientSecret, tenantId))
                    .buildClient();
    
            try {
                Message message = new Message();
                message.subject = "Test Email without Attachment";
    
                ItemBody body = new ItemBody();
                body.contentType = BodyType.TEXT;
                body.content = "This is a test email.";
                message.body = body;
    
                LinkedList<Recipient> toRecipients = new LinkedList<>();
                Recipient recipient = new Recipient();
                EmailAddress emailAddress = new EmailAddress();
                emailAddress.address = recipientEmail;
                recipient.emailAddress = emailAddress;
                toRecipients.add(recipient);
                message.toRecipients = toRecipients;
    
                // Commented out the attachment adding part
                /*
                FileAttachment fileAttachment = new FileAttachment();
                fileAttachment.oDataType = "#microsoft.graph.fileAttachment";
                fileAttachment.name = "testfile.txt";
                fileAttachment.contentBytes = "Sample file content.".getBytes(StandardCharsets.UTF_8);
    
                LinkedList<Attachment> attachmentList = new LinkedList<>();
                attachmentList.add(fileAttachment);
    
                AttachmentCollectionResponse attachmentCollectionResponse = new AttachmentCollectionResponse();
                attachmentCollectionResponse.value = attachmentList;
    
                AttachmentCollectionPage attachmentCollectionPage = new AttachmentCollectionPage(attachmentCollectionResponse, null);
                message.attachments = attachmentCollectionPage;
                */
    
                if (message.attachments != null &&
                        message.attachments.getCurrentPage() != null &&
                        message.attachments.getCurrentPage().size() > 0) {
                    System.out.println("Attachment is present before sending.");
                } else {
                    System.out.println("No attachment found before sending.");
                }
    
                graphClient.users(senderUserId)
                        .sendMail(UserSendMailParameterSet
                                .newBuilder()
                                .withMessage(message)
                                .withSaveToSentItems(true)
                                .build())
                        .buildRequest()
                        .post();
    
                System.out.println("Email sent successfully.");
    
                Thread.sleep(5000);
    
                var sentMessagesPage = graphClient.users(senderUserId)
                        .mailFolders("sentitems")
                        .messages()
                        .buildRequest()
                        .top(1)
                        .orderBy("receivedDateTime desc")
                        .select("subject,hasAttachments,receivedDateTime")
                        .get();
    
                if (sentMessagesPage.getCurrentPage() != null &&
                        sentMessagesPage.getCurrentPage().size() > 0) {
                    Message latestSentMessage = sentMessagesPage.getCurrentPage().get(0);
                    System.out.println("Latest Sent Mail Subject: " + latestSentMessage.subject);
                    if (Boolean.TRUE.equals(latestSentMessage.hasAttachments)) {
                        System.out.println("Confirmed: Sent mail has attachments.");
                    } else {
                        System.out.println("Confirmed: Sent mail has NO attachments.");
                    }
                } else {
                    System.out.println("No messages found in Sent Items.");
                }
    
            } catch (Exception e) {
                System.out.println("Failed: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
    

    Response:

    enter image description here

    When I ran the same code by uncommenting the attachment part, I was able to successfully detect attachment status both before and after sending.

    enter image description here

    Let me know if you have any other questions or need any further assistance.

    Hope this helps!


    If this answer was helpful, please click "Accept the answer" and mark Yes, as this can help other community members.

    User's image

    If you have any other questions or are still experiencing issues, feel free to ask in the "comments" section, and I'd be happy to help.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.