gpt4 book ai didi

c# - 在 C# 中为 Gmail API 创建消息

转载 作者:太空狗 更新时间:2023-10-29 18:14:54 25 4
gpt4 key购买 nike

我正在考虑在我正在开发的应用程序中使用 Gmail API。但是,我不确定如何将他们的 Java 或 Python 示例更改为 C#。现有样本究竟如何转换?

Sample found here.

最佳答案

这是我能够开始工作的,使用 MimeKit .

public void SendEmail(MyInternalSystemEmailMessage email)
{
var mailMessage = new System.Net.Mail.MailMessage();
mailMessage.From = new System.Net.Mail.MailAddress(email.FromAddress);
mailMessage.To.Add(email.ToRecipients);
mailMessage.ReplyToList.Add(email.FromAddress);
mailMessage.Subject = email.Subject;
mailMessage.Body = email.Body;
mailMessage.IsBodyHtml = email.IsHtml;

foreach (System.Net.Mail.Attachment attachment in email.Attachments)
{
mailMessage.Attachments.Add(attachment);
}

var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);

var gmailMessage = new Google.Apis.Gmail.v1.Data.Message {
Raw = Encode(mimeMessage)
};

Google.Apis.Gmail.v1.UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(gmailMessage, ServiceEmail);

request.Execute();
}

public static string Encode(MimeMessage mimeMessage)
{
using (MemoryStream ms = new MemoryStream())
{
mimeMessage.WriteTo(ms);
return Convert.ToBase64String(ms.GetBuffer())
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
}

注意:如果您遇到电子邮件退回问题,可能是因为没有设置 ReplyToList 字段。请参阅:GMail API Emails Bouncing

关于c# - 在 C# 中为 Gmail API 创建消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24728793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com