StackOverflow上一个已回答的问题表明,在电子邮件正文中添加html-markup就可以了.这个解决方案是否正确
但是,如果收件人的电子邮件服务器/客户端不支持HTML电子邮件呢?
例如,当使用Apache commons电子邮件时,我会执行以下操作:
// set the html message email.setHtmlMsg("Our logo - "); // set the alternative message email.setTextMsg("Your email client does not support HTML messages");
如果收件人电子邮件服务器/客户端不支持HTML,有没有办法告诉Gmail API哪些电子邮件会退回?
PS我对Java代码示例特别感兴趣.
谢谢
要给出两个替代方案,您可以设置Content-Type
to mixed/alternative
而不是:text/plain
或者text/html
:
如果我们想在尝试了这一点API探险家,我们只是使用Base64编码的邮件,并使其网址安全的所有替换/
与_
和所有+
与-
.
在开发者控制台中:
btoa( "Subject: Example Subject\r\n" + "From:\r\n" + "To: \r\n" + "Content-Type: multipart/alternative; boundary=\"foo_bar\"\r\n\r\n" + "--foo_bar\r\n" + "Content-Type: text/plain; charset=UTF-8\r\n\r\n" + "*Bold example message text*\r\n\r\n" + "--foo_bar\r\n" + "Content-Type: text/html; charset=UTF-8\r\n\r\n" + " Bold example message text\r\n\r\n" + "--foo_bar--" ).replace(/\+/g, '-').replace(/\//g, '_'); POST https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token={YOUR_API_KEY} { "raw": "U3ViamVjdDogRXhhbXBsZSBTdWJqZWN0DQpGcm9tOiA8ZXhhbXBsZUBnbWFpbC5jb20-DQpUbzogPGV4YW1wbGVAZ21haWwuY29tPg0KQ29udGVudC1UeXBlOiBtdWx0aXBhcnQvYWx0ZXJuYXRpdmU7IGJvdW5kYXJ5PSJmb29fYmFyIg0KDQotLWZvb19iYXINCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbjsgY2hhcnNldD1VVEYtOA0KDQoqQm9sZCBleGFtcGxlIG1lc3NhZ2UgdGV4dCoNCg0KLS1mb29fYmFyDQpDb250ZW50LVR5cGU6IHRleHQvaHRtbDsgY2hhcnNldD1VVEYtOA0KDQo8ZGl2IGRpcj0ibHRyIj48Yj5Cb2xkIGV4YW1wbGUgbWVzc2FnZSB0ZXh0PC9iPjwvZGl2Pg0KDQotLWZvb19iYXItLQ==" }
要在Java中执行等效操作,您可以:
Message message = new MimeMessage(session); Multipart multiPart = new MimeMultipart("alternative"); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(text, "utf-8"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html; charset=utf-8"); multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); ByteArrayOutputStream output = new ByteArrayOutputStream(); message.writeTo(output); String rawEmail = Base64.encodeBase64URLSafeString(output.toByteArray()); Message message = new Message(); message.setRaw(rawEmail); message = service.users().messages().send(userId, message).execute();