Mike
Mike

Reputation: 21

How do you send MIME format emails using Microsoft Graph Java SDK?

The official documentation does not provide an example for any SDK's (including the Java SDK): https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=java#example-4-send-a-new-message-using-mime-format. As there is no example, I have tried in vain to send the MIME content using the SDK (microsoft-graph 5.0.0):

Message sending = new Message();
ItemBody body = new ItemBody();
final String mimeMessageRFC822 = input.getMimeMessageRFC822();
body.content = Base64.getMimeEncoder().encodeToString(mimeMessageRFC822.getBytes());
sending.body = body;

GraphServiceClient service = getService(acHost, configuration);
service
    .me()
    .sendMail(UserSendMailParameterSet.newBuilder().withMessage(sending).withSaveToSentItems(true).build())
    .buildRequest(new HeaderOption("Content-Type", "text/plain"))
    .post();

The above code sets the request's content-type to text/plain, however the request body that is being sent is JSON (xxxxxx below is a placeholder for a valid Base64 encoded MIME content string).

{
    "message":
    {
        "body":
        {
            "content": xxxxxx
        }
    },
    "saveToSentItems": true
}

The response is a 404, stating:

GraphServiceException: Error code: ErrorMimeContentInvalidBase64String Error message: Invalid base64 string for MIME content.

I can understand why it is responding with this error as the graph endpoint is parsing the text/plain content as base64 encoded MIME but finds the JSON structure instead. I have been on a video call with a Microsoft Graph support agent, and they have seen that my MIME content is valid. Sadly, they are not able to help with the Microsoft Graph Java SDK even though it is developed by Microsoft!

This suggests that we are not supposed to use the Java SDK at all for sending MIME formatted emails. Is this correct? Surely it can't be otherwise what is the point of a library that can receive MIME formatted emails but can't send them? Does anyone have a solution?

Upvotes: 1

Views: 3015

Answers (1)

Mike
Mike

Reputation: 21

For now at least the solution is to send a CustomRequest with MIME content instead of using the fluent API provided by the Graph client.

final String encodedContent = Base64.getMimeEncoder().encodeToString(mimeMessageRFC822.getBytes());
CustomRequest<String> request = new CustomRequest<>(requestUrl, service, List.of(new HeaderOption("Content-Type", "text/plain")), String.class);
request.post(encodedContent);

Upvotes: 1

Related Questions