我有以下 Java 代码,尝试创建 MIME 消息并将其发送到 Microsoft graph。我尝试了以下几个示例(请参阅代码中的注释),但仍然收到错误。我的代码是:
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);
}
}
和
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."}}
有人知道如何对 mime 消息进行编码吗?
我遇到的问题是:
encodedEmail = Base64.encodeBase64URLSafeString(bytes);
相反,我需要做的是:
byte[] encodedBytesNewWay = java.util.Base64.getEncoder().encode(utf8Bytes);
String encodedString = new String(encodedBytesNewWay);