编辑:我使用SendGrid SMTP在我的。net 4.7.1 web应用程序中发送自动电子邮件。电子邮件发送得很好,除了内联附件(公司标志等),附件不会随它一起发送。我刚刚继承了这个项目,显然这工作之前使用MailGun,但切换到SendGrid SMTP它不再工作。
我有从磁盘读取的图像,只有错误的图像。它取了一张我之前有过的图片——但我已经完全删除了,并在我的HD中搜索了——并将其保存到我在下面的代码中指定的目录中。名称是正确的,但实际保存的字节内容是错误的。
这是附加图像-但不显示它内联,即使文件名是相同的cid:引用在标签。
这是生成的电子邮件正文的一部分,应该引用这个内联附件
<img src="cid:Email-Logo-USA.jpg" alt="Logo" style="width: 100%; max-width: 380px;" />
这是处理所有电子邮件和附件发送的类
internal class MailGunEmailService : IEmailService
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private readonly string path = "~/App_Data/attachments/";
public void Send(
MailAddress from,
ICollection<MailAddress> to,
ICollection<MailAddress> cc,
ICollection<MailAddress> bcc,
string subject,
string body,
ICollection<Attachment> attachments)
{
var smtpClient = new SmtpClient();
var message = new MailMessage();
message.From = new System.Net.Mail.MailAddress(from.ToString());
//var request = new RestRequest();
if (to != null && to.Count > 0)
foreach (var emailTo in to)
message.To.Add(new System.Net.Mail.MailAddress(emailTo.ToString()));
if (cc != null && cc.Count > 0)
foreach (var carbonCopy in cc)
message.CC.Add(new System.Net.Mail.MailAddress(carbonCopy.ToString()));
if (bcc != null && bcc.Count > 0)
foreach (var blindCarbonCopy in bcc)
message.Bcc.Add(new System.Net.Mail.MailAddress(blindCarbonCopy.ToString()));
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
// Attachments currently do not work
// Need to get the path(s) to the file(s) and add to email using System.Net.Mail.Attachments()
if (attachments != null)
{
foreach (var attachment in attachments.Where(a => !a.Inline))
message.Attachments.Add(new System.Net.Mail.Attachment(attachment.FileName));
foreach (var attachment in attachments.Where(a => a.Inline))
{
if (!Directory.Exists(HostingEnvironment.MapPath(path)))
Directory.CreateDirectory(HostingEnvironment.MapPath(path) ?? string.Empty);
var attachmentPath = Path.Combine(HostingEnvironment.MapPath(path) ?? string.Empty,
attachment.FileName);
File.WriteAllBytes(attachmentPath, attachment.Content);
var att = new System.Net.Mail.Attachment(attachmentPath);
att.ContentDisposition.Inline = true;
att.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
message.Attachments.Add(att);
}
}
smtpClient.Send(message);
}
}
Attachment.FileName
属性指定附件的文件名,但不提供文件内容本身。
要解决这个问题,您可以将文件内容上传到MemoryStream对象,然后使用Attachment.ContentStream
属性而不是Attachment.FileName
将其附加到电子邮件。
...
if (attachment.Inline)
{
var stream = new MemoryStream(File.ReadAllBytes(attachment.FileName));
var inlineAttachment = new System.Net.Mail.Attachment(stream, attachment.Name, attachment.ContentType);
inlineAttachment.ContentId = attachment.ContentId;
inlineAttachment.ContentDisposition.Inline = true;
message.Attachments.Add(inlineAttachment);
}
else
{
message.Attachments.Add(new System.Net.Mail.Attachment(attachment.FileName));
}
...