直到今天,我一直在为此苦苦挣扎。
我所做的是调整此链接上的解决方案以用于草稿。
http://jason.pettys.name/2014/10/27/sending-email-with-the-gmail-api-in-net-c/
Jason 使用名为 AE.Net.Mail 的 nuget 将邮件对象序列化为 RFC 2822。
我所做的是我安装了两个 nuget
Install-Package Google.Apis.Gmail.v1
Install-Package AE.Net.Mail
之后我创建了两种方法
static GmailService Service;
public static void CriaService(string emailaConectar)
{
var certificate = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ClientCredentials.CertificatePath), ClientCredentials.ClientSecret, X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(ClientCredentials.ServiceAccountEmail)
{
Scopes = new[] { GmailService.Scope.GmailCompose },
User = emailaConectar
}.FromCertificate(certificate)) { };
Service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ClientCredentials.ApplicationName,
});
}
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("=", "");
}
在我的 Main 方法中,我这样设计
CriaService("xpto@gmail.com");
var msg = new AE.Net.Mail.MailMessage
{
Subject = "Your Subject",
Body = "Hello, World, from Gmail API!",
From = new MailAddress("xpto@gmail.com")
};
msg.To.Add(new MailAddress("someone@gmail.com"));
msg.ReplyTo.Add(msg.From);
var msgStr = new StringWriter();
msg.Save(msgStr);
Message m = new Message();
m.Raw = Base64UrlEncode(msgStr.ToString());
var draft = new Draft();
draft.Message = m;
try
{
Service.Users.Drafts.Create(draft, "xpto@opportunity.com.br").Execute();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}