I am attempting to generate a Gmail draft message in a winforms application using C#. The draft message needs to be in HTML format and able to contain an attachment.
I was able to generate a draft with an attachment using AE.Net.Mail
, but the draft message was in plain text (I couldn't figure out how to code AE.Net.Mail
to give me an HTML Gmail draft message).
In an attempt to get the message into an HTML format I used MimeKit to take a System.Net.Mail
message and convert it into a MimeMessage
message. However, I cannot figure out how to get the MIME message into in an RFC 2822 formatted and URL-safe base64 encoded string as required by the Gmail draft specification.
Here is the code from the MimeKit Conversion attempt:
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
Here is the code using AE.Net.Mail
that works, but generates the body of the Gmail draft as plain text (based on this article by Jason Pettys):
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("=", "");
}
Is there a way to convert MimeKit's MimeMessage
message into an RFC 2822 formatted and URL-safe base64 encoded string so that it can be generated as a Gmail draft? Failing that, is there a way to create an AE.Net.Mail
message in HTML format prior to encoding it? All help is greatly appreciated.