HeronAlgoSearch
HeronAlgoSearch

Reputation: 1877

How to Convert MimeMessage to String for Microsoft Graph

I have the following Java Code that tries to create a MIME message and send it to Microsoft graph. I have tried following several examples (see comments in code) but I still get an error. My code is:

private MimeMessage createMimeMessageEmail(EmailDetails emailDetails, boolean includeUnsubscribeLink) {

        try {
            Session session = Session.getDefaultInstance(new Properties());
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(emailDetails.getFrom());
            mimeMessage.setSubject(emailDetails.getSubject());
            // https://stackoverflow.com/questions/5068827/how-do-i-send-an-html-email

            mimeMessage.setContent(emailDetails.getHtmlBody(), "text/html; charset=utf-8");
            mimeMessage.addRecipient(jakarta.mail.Message.RecipientType.TO, new InternetAddress(emailDetails.getTo()));
            return mimeMessage;

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }

and

private void doMyTest(EmailDetails emailDetails, OAuthAccessToken accessToken) {

        MimeMessage mimeMessage = createMimeMessageEmail(emailDetails, true);
        String encodedEmail = null;
        try {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            mimeMessage.writeTo(buffer);
            byte[] bytes = buffer.toByteArray();
            encodedEmail = Base64.encodeBase64URLSafeString(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        try {
            HttpPost post = new HttpPost("https://graph.microsoft.com/v1.0/me/sendMail");
            post.setEntity(new StringEntity(encodedEmail));
            post.setHeader("Content-type", "text/plain");
            post.setHeader("Authorization", "Bearer " + accessToken.getTokenValue());
            try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

                Integer intV = httpclient.execute(post, httpResponse -> {
                    // Get status code
                    int responseCode = httpResponse.getCode();
                    String json = EntityUtils.toString(httpResponse.getEntity());
                    if (responseCode != 200) {
                        return responseCode;
                    }
//                    String json = EntityUtils.toString(httpResponse.getEntity());
                    return responseCode;
                });
            }
        } catch (Exception e) {
        }
    }
    ```

But I keep getting:
```{"error":{"code":"ErrorMimeContentInvalidBase64String","message":"Invalid base64 string for MIME content."}}

Does anyone know how to encode the mime message?

Upvotes: 0

Views: 59

Answers (1)

HeronAlgoSearch
HeronAlgoSearch

Reputation: 1877

The issue I had was: encodedEmail = Base64.encodeBase64URLSafeString(bytes); Rather than that, I needed to do:

byte[] encodedBytesNewWay = java.util.Base64.getEncoder().encode(utf8Bytes);
            String encodedString = new String(encodedBytesNewWay);

Upvotes: 0

Related Questions