【发布时间】:2016-06-09 20:43:25
【问题描述】:
我正在尝试使用 C# 在 winforms 应用程序中生成 Gmail 草稿消息。草稿消息需要采用 HTML 格式并且能够包含附件。
我能够使用AE.Net.Mail 生成带有附件的草稿,但草稿邮件是纯文本的(我不知道如何编码AE.Net.Mail 来给我一个HTML Gmail 草稿邮件)。
为了将消息转换为 HTML 格式,我使用 MimeKit 获取 System.Net.Mail 消息并将其转换为 MimeMessage 消息。但是,我无法弄清楚如何按照 Gmail 草案规范的要求将 MIME 消息放入 RFC 2822 格式和 URL 安全的 base64 编码字符串中。
这是 MimeKit 转换尝试的代码:
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
MailMessage msg = new MailMessage(); //System.Net.Mail
msg.IsBodyHtml = true;
msg.Subject = "HTML Email";
msg.Body = "<a href = 'http://www.yahoo.com/'>Enjoy Yahoo!</a>";
msg.Attachments.Add(file);
MimeMessage message = MimeMessage.CreateFromMailMessage(msg); //MimeKit conversion
//At this point I cannot figure out how to get the MIME message into
//an RFC 2822 formatted and URL-safe base64 encoded string
//as required by the Gmail draft specification
//See working code below for how this works in AE.Net.Mail
下面是使用 AE.Net.Mail 的代码,它可以正常工作,但会将 Gmail 草稿的正文生成为纯文本(基于 Jason Pettys 的 this article):
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
var msg = new AE.Net.Mail.MailMessage //msg created in plain text not HTML format
{
Body = "<a href = 'http://www.yahoo.com/'>Enjoy Yahoo!</a>"
};
var bytes = System.IO.File.ReadAllBytes(filePath);
AE.Net.Mail.Attachment file = new AE.Net.Mail.Attachment(bytes, @"application/pdf", FileName, true);
msg.Attachments.Add(file);
var msgStr = new StringWriter();
msg.Save(msgStr);
Message m = new Message();
m.Raw = Base64UrlEncode(msgStr.ToString());
Draft draft = new Draft(); //Gmail draft
draft.Message = m;
service.Users.Drafts.Create(draft, "me").Execute();
private static string Base64UrlEncode(string input)
{
var inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
// Special "url-safe" base64 encode.
return Convert.ToBase64String(inputBytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}
有没有办法将 MimeKit 的 MimeMessage 消息转换为 RFC 2822 格式和 URL 安全的 base64 编码字符串,以便可以将其生成为 Gmail 草稿?如果做不到这一点,有没有办法在编码之前以 HTML 格式创建 AE.Net.Mail 消息?非常感谢所有帮助。
【问题讨论】:
-
您有几篇关于 Drafts API Gmail 的帖子。您是否尝试下载 EML 格式的草稿或消息?
-
@Kiquenet 您在此问题下方的先前评论中提出了问题,我在回复评论中回答,然后两者都被删除。 (也许是你?)现在你在评论中发布了上述问题。我在这篇文章中的问题是一年多前解决的。我不知道您为什么要进一步询问我是否尝试过 EML 格式。我的问题已经得到解答。我确实发布了三个不同的问题。两个得到了答复,一个保持打开状态(我应该关闭它并将其放在我的待办事项列表中)。感谢您的关注,但我不再需要这个特定问题的帮助。
标签: c# winforms google-api gmail mimekit