gpt4 book ai didi

c# - 如何在 ASP.NET 中使用具有 HTML 正文 + 附件的 GMAIL API 发送电子邮件

转载 作者:行者123 更新时间:2023-11-30 20:37:45 27 4
gpt4 key购买 nike

var msg = new AE.Net.Mail.MailMessage
{
Subject = subject,
Body = bodyhtml,
From = new System.Net.Mail.MailAddress("myemail")

};
foreach (string add in vendorEmailList.Split(','))
{
if (string.IsNullOrEmpty(add))
continue;

msg.To.Add(new System.Net.Mail.MailAddress(add));
}

msg.ReplyTo.Add(msg.From); // Bounces without this!!
msg.ContentType = "text/html";

////attachment code

foreach (string path in attachments)
{
var bytes = File.ReadAllBytes(path);
string mimeType = MimeMapping.GetMimeMapping(path);
AE.Net.Mail.Attachment attachment = new AE.Net.Mail.Attachment(bytes, mimeType, Path.GetFileName(path), true);
msg.Attachments.Add(attachment);
}
////end attachment code

var msgStr = new StringWriter();
msg.Save(msgStr);

Message message = new Message();
message.Raw = Base64UrlEncode(msgStr.ToString());
var result = gmailService.Users.Messages.Send(message, "me").Execute();

此代码无需附件即可工作,但带有附件而不是直接附件字节 [] 出现在收件箱中。

如果我删除 msg.ContentType = "text/html"这行,那么它可以工作,但 html 不会在电子邮件中呈现,显示为纯文本。

我想发送 HTML 正文和附件,请帮忙。

最佳答案

 MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.Body = bodyhtml;
mail.From = new MailAddress("myemail");
mail.IsBodyHtml = true;

foreach (string add in vendorEmailList.Split(','))
{
if (string.IsNullOrEmpty(add))
continue;

mail.To.Add(new MailAddress(add));
}

foreach (string add in userEmailList.Split(','))
{
if (string.IsNullOrEmpty(add))
continue;

mail.CC.Add(new MailAddress(add));
}

foreach (string path in attachments)
{
//var bytes = File.ReadAllBytes(path);
//string mimeType = MimeMapping.GetMimeMapping(path);
Attachment attachment = new Attachment(path);//bytes, mimeType, Path.GetFileName(path), true);
mail.Attachments.Add(attachment);
}
MimeKit.MimeMessage mimeMessage = MimeMessage.CreateFromMailMessage(mail);

Message message = new Message();
message.Raw = Base64UrlEncode(mimeMessage.ToString());
var result = gmailService.Users.Messages.Send(message, "me").Execute();

经过一番努力,我找到了解决方案。使用 System.Net.Mail.MailMessage 和 MimeKit 将其转换为原始字符串,而不是 AE.Net.Mail.MailMessage。现在带有附件的 html 正文工作正常。

关于c# - 如何在 ASP.NET 中使用具有 HTML 正文 + 附件的 GMAIL API 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35763607/

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