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();
此代码无需附件即可工作,但可以使用附件而不是附件直接在收件箱中显示byte []。
如果我删除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();
经过大量的努力,我找到了解决方案。而不是AE.Net.Mail.MailMessage使用System.Net.Mail.MailMessage和MimeKit将其转换为原始字符串。现在带有附件的html主体可以正常工作。
关于c# - 如何在ASP.NET中使用具有HTML正文和附件的GMAIL API发送电子邮件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35763607/