通过 Gmail API 发送 HTML 带有纯文本回退的电子邮件

Send HTML email with plain text fallback via Gmail API

Whosebug 的

An answered question 建议在电子邮件正文中添加 html-标记即可。该解决方案正确吗?

但是如果收件人的邮箱 server/client 不支持 HTML 邮箱怎么办?

例如使用 Apache commons email 时,我执行以下操作:

// set the html message
email.setHtmlMsg("<html>Our logo - <img src=\"cid:"+cid+"\"></html>");
// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");

如果收件人电子邮件 server/client 不支持 HTML,有什么方法可以告诉 Gmail API 回退到哪个电子邮件?

P.S。 我对 Java 代码示例特别感兴趣。

谢谢

要给出两个备选方案,您可以将 Content-Type 设置为 mixed/alternative 而不是 text/plaintext/html:

如果我们想在 API explorer 中尝试这个,我们只需对邮件进行 Base64 编码,并通过将所有 / 替换为 [=17] 使其 url 安全=] 和所有 +-.

在开发者控制台中:

btoa(
  "Subject: Example Subject\r\n" +
  "From: <example@gmail.com>\r\n" +
  "To: <example@gmail.com>\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" +

  "<div dir=\"ltr\"><b>Bold example message text</b></div>\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();

要对来自 Throlle 的上述答案进行更新。 上面有一些差异,可能与更高版本的 gmail api

发送消息并遵循他们默认提供的发送标准电子邮件的标准:

这是在 grails 中,但您可以轻松更改 java,此 html 之前的控制器内容可以是 found here。也许当我完成我正在做的事情并有机会更新 github 网站时,所有这些例子:

在控制器中 sendHTMLEmail:

  def sendHTMLEmail() {
        String emailBox='me@gmail.com'
        String to ='someuser@domain.com'
        String html="<html><body><table><tr><td><b>aa</b></td><td>bb</td></tr></table><h1>html content</h1></body></html>"
        MimeMessage content = gmailService.createHTMLEmail(to,emailBox,'gmail test','testing gmail via app',html)
        def message = gmailService.sendMessage(gmail,'me',content)
        render "=== ${message.id}"
}

服役中createHTMLEmail

public static MimeMessage createHTMLEmail(String to, String from, String subject, String text, String html) {
        Properties props = new Properties()
        Session session = Session.getDefaultInstance(props, null)

        MimeMessage email = new MimeMessage(session)
        Multipart multiPart = new MimeMultipart("alternative")
        email.setFrom(new InternetAddress(from))
        email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to))
        email.setSubject(subject)

        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)
        email.setContent(multiPart)
        return email
    }

然后他们的标准提供了sendMessage(下面的位可以在github link上找到):

public static Message sendMessage(Gmail service,String userId,MimeMessage emailContent) throws MessagingException, IOException {
        try {
            Message message = createMessageWithEmail(emailContent)
            message = service.users().messages().send(userId, message).execute()
            return message
        } catch (Exception e) {
            //log.error "${e}"
        }
    }

和 createMessageWithEmail

public static Message createMessageWithEmail(MimeMessage emailContent) throws MessagingException, IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream()
        emailContent.writeTo(buffer)
        byte[] bytes = buffer.toByteArray()
        String encodedEmail = Base64.encodeBase64URLSafeString(bytes)
        Message message = new Message()
        message.setRaw(encodedEmail)
        return message
    }