我需要帮助发送电子邮件附件使用c#中的Gmail Api。
我已经阅读了谷歌网站上发送电子邮件附件,但例子是在java。
发布于 2014-10-16 23:56:53
使用Gmail API发送附件并没有什么特别之处。无论采用哪种方式,Gmail API message.send()都会在message.raw字段中接收完整的RFC822电子邮件消息( full安全base64编码)。主要技巧是用您的语言构建这样一个RFC822电子邮件消息字符串。我想在C#中有一些MIME消息库,而这是主要的问题是找到这些库。我不做C#,但javax.internet.mail.MimeMessage在java中运行得很好,'email‘模块对python也很好。
另一篇文章似乎与此相关:How to send multi-part MIME messages in c#?
发布于 2017-10-24 11:01:29
答案为时已晚,但将其张贴出来,以防有人需要:)
这需要MimeKit库:可以从NuGet安装。
代码:
public void SendHTMLmessage()
{
//Create Message
MailMessage mail = new MailMessage();
mail.Subject = "Subject!";
mail.Body = "This is <b><i>body</i></b> of message";
mail.From = new MailAddress("fromemailaddress@gmail.com");
mail.IsBodyHtml = true;
string attImg = "C:\\Documents\\Images\\Tulips.jpg OR Any Path to attachment";
mail.Attachments.Add(new Attachment(attImg));
mail.To.Add(new MailAddress("toemailaddress.com.au"));
MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);
Message message = new Message();
message.Raw = Base64UrlEncode(mimeMessage.ToString());
//Gmail API credentials
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scope,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
//Send Email
var result = service.Users.Messages.Send(message, "me/OR UserId/EmailAddress").Execute();
}
作用域可以是:
GmailSend或GmailModify
static string[] Scope = { GmailService.Scope.GmailSend };
static string[] Scope = { GmailService.Scope.GmailModify };
Base64UrlEncode函数:
private string Base64UrlEncode(string input)
{
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(inputBytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}
发布于 2015-01-25 13:36:51
我在VB.net中有一个例子。GMail API Emails Bouncing。
Google页面仅提供Java和Python版本的示例。Java示例中使用的对象在.Net版本的API中不可用。翻译这些例子是不可能的。
幸运的是,在C#/VB中也很容易做到这一点。只需使用普通的老式Net.Mail.MailMessage创建一个包含附件的消息,然后使用MimeKit (NuGet it)将消息转换为字符串,并将字符串(经过Base64编码后)传递给Gmail API的message.send的原始字段。
https://stackoverflow.com/questions/26397894
复制相似问题