简体   繁体   English

使用Gmail API和Javascript发送HTML格式的电子邮件

[英]Send HTML formatted email using Gmail API and Javascript

The following javascript code successfully sends an email message via the Gmail API. 以下javascript代码通过Gmail API成功发送了电子邮件。 However the table formatting, specifically the table and column (cell) width settings, seem to be ignored. 但是,表格格式,特别是表格和列(单元格)的宽度设置,似乎被忽略了。

function sendMail(email) {
    var to = email;
    var subject = "HTML formatted email";
    var content = "";
    content += "<html><body>";
    content += "<table width='100%'><tr><td>"; // Outer table
    content += "<table width='60%'>"; // Nested table
    content += "<tr><td width='70%'>This is a row</td><td width='30%'>999999</td></tr>";
    content += "<tr><td width='70%'>So is this</td><td width='30%'>9999</td></tr>";
    content += "</table>";
    content += "</td></tr></table>";
    content += "</body></html>";
    var email =
            "From: 'me'\r\n" +
            "To: " + to + "\r\n" +
            "Subject: " + subject + "\r\n" +
            "Content-Type: text/html; charset=utf-8\r\n" +
            "Content-Transfer-Encoding: quoted-printable\r\n\r\n" +
            content;
    var base64EncodedEmail = window.btoa(email).replace(/\+/g, "-").replace(/\//g, "_");
    var request = gapi.client.gmail.users.messages.send({
        "userId": "me",
        "resource": {
            "raw": base64EncodedEmail
        }
    });
    request.execute();
}

The email message looks as follows: 该电子邮件如下所示:

This is a row 999999
So is this    9999

Everything I've researched on sending HTML formatted email messages says to use nested tables and inline styling. 我研究过的有关发送HTML格式电子邮件的所有研究都说要使用嵌套表和内联样式。 Why is my width styling not working? 为什么我的宽度样式不起作用?

After much searching, experimentation and testing I finally figured out that I needed to set the content-transfer-encoding value to base64: 经过大量的搜索,试验和测试,我最终发现我需要将content-transfer-encoding值设置为base64:

var email =
        "From: 'me'\r\n" +
        "To: " + to + "\r\n" +
        "Subject: " + subject + "\r\n" +
        "Content-Type: text/html; charset='UTF-8'\r\n" +
        "Content-Transfer-Encoding: base64\r\n\r\n" +
        "<html><body>" +
        content +
        "</body></html>";

Hope this saves others with similar question some time. 希望这可以节省其他有类似问题的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM