为什么Gmail API无法从C#以HTML格式发送电子邮件?

时间:2018-07-23 18:50:28

标签: c# api gmail

我正在尝试使用Gmail API从C#发送HTML电子邮件。电子邮件已发送,但Gmail拒绝承认它应为HTML电子邮件。

这是我正在使用的代码:

var template = @"from: {1}{4}to: {0}{4}subject: {2}{4}MIME-Version: 1.0{4}Content-Type: text/html; charset=UTF-8{4}Content-Transfer-Encoding: base64{4}{4}{3}";
body = HttpUtility.HtmlEncode(body);
var result = string.Format(template, to, from, subject, body, "\r\n");
result = Convert.ToBase64String(Encoding.UTF8.GetBytes(result));

var gMessage = new Message()
{
    Raw = result
};
service.Users.Messages.Send(gMessage, "me").Execute();

这是在编码为base64之前结果字符串的样子:

from: test@test.com
to: test@test2.com
subject: testSubject
MIME-Version: 1.0
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: base64

<html><head>

<title>Push Email</title>   

</head>    
<body> blah  

</body></html>

(出于隐私考虑,该应用实际上使用了真实的电子邮件地址,在上面的示例中我已将其替换为“ test @ ...”。)

我尝试了标头排列,内容传输编码(base64、7bit,8bit等),内容类型字符集(ascii,utf8等)的所有可能组合,我尝试使用UrlEncode代替HtmlEncode,但使用电子邮件正文要么显示为未渲染的HTML,要么显示为编码的url字符串(取决于我使用的是html编码还是url编码,以及我指定的竞争转换编码)。

重点是,邮件正在运行,正在发送正文,但它只是顽固地拒绝呈现HTML。我要么得到这个:

<html><head> <title>Push Email</title> </head> <body> blah </body></html>

或者这个:

%3chtml%3e%3chead%3e%0d%0a%0d%0a%3ctitle%3ePush+Email%3c%2ftitle%3e+++%0d%0a+%0d%0a%3c%2fhead%3e++++%0d%0a%3cbody%3e+blah++%0d%0a++++%0d%0a%3c%2fbody%3e%3c%2fhtml%3e

或者这个:

&lt;html&gt;&lt;head&gt; &lt;title&gt;Push Email&lt;/title&gt; &lt;/head&gt; &lt;body&gt; blah &lt;/body&gt;&lt;/html&gt;

我只会发送SMTP电子邮件,但是出于安全考虑,如果您对该帐户进行2因子验证(我已经并且不打算停用该帐户),Google不会允许它。

此外,我只是将MIME消息构建为常规字符串。这可能与它有关,但我不知道。我不打算使用任何第三方nuget包/库,例如MimeKit。我只想要一个C#解决方案。

最后,我需要能够发送HTML电子邮件,以便可以按照我的应用业务逻辑发送链接。

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

我终于明白了。首先,不得对邮件正文进行转义,而应对整个MIME字符串进行转义。但是,如前所述,如果我不对正文进行编码,那么API会抱怨字节字节无效。

问题在于,应以URL安全的方式对生成的base64字符串进行编码。 Gmail API guide上的python代码使用一种称为urlsafe_b64encode的方法,该方法与普通的base 64方法不同,因为生成的字符串是URL安全的。

我以为可以在C#中使用HTML或URL编码来复制它,然后使用标准的Convert.ToBase64String方法将MIME字符串转换为base64,但是我错了。在搜索MSDN网站后,我终于找到了HttpServerUtility.UrlTokenEncode方法,该方法与urlsafe_b64encode python方法的作用相同,该方法是将字符串编码为URL安全变体并将其转换为base64。最终的代码将变为:

// Template for the MIME message string (with text/html content type)
var template = @"from: {1}{4}to: {0}{4}subject: {2}{4}MIME-Version: 1.0{4}Content-Type: text/html; charset=UTF-8{4}Content-Transfer-Encoding: base64{4}{4}{3}";
// Fill in MIME message fields
var result = string.Format(template, to, from, subject, body, "\r\n");
// Get the bytes from the string and convert it to a URL safe base64 string
result = HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(result));

// Instantiate a Gmail API message and assign it the encoded MIME message
var gMessage = new Message()
{
    Raw = result
};
// Use the Gmail API Service to send the email
service.Users.Messages.Send(gMessage, "me").Execute();

答案 1 :(得分:0)

您的身体看起来像是被HtmlEncode传递了两次,即<一次传递成为&lt;,两次传递成为&amp;lt;,这就是您拥有的。因为您没有在编码之前发布设置body的原始代码,所以我只能说您必须先将其作为result字符串,然后再进行base64编码:

from: test@test.com
to: test@test2.com
subject: testSubject
MIME-Version: 1.0
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: base64

<html><head>

<title>Push Email</title>   

</head>    
<body> blah  

</body></html>

要获取此信息,您可以替换此行

body = HttpUtility.HtmlEncode(body);

以此

body = HttpUtility.HtmlDecode(body);

答案 2 :(得分:0)

真的只需要选项“ IsBodyHtml = true”:

using System.Net;
using System.Net.Mail;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var html = "<html><head><body><h1>hello world!</h1></body><head></html>";
            var from = "me@here.com";
            var to = "them@there.com";

            var msg = new MailMessage(from, to)
            {
                Subject = "My Subject",
                Body = html,
                IsBodyHtml = true
            };
            SendGmail("myUserName", "myPassword", msg);
        }

        public static void SendGmail(string username, string password, MailMessage msg)
        {
            var client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential(username, password);
            client.Send(msg);
        }
    }
}