【问题标题】:Image in body of the Mail C#邮件 C# 正文中的图像
【发布时间】:2015-08-04 15:51:05
【问题描述】:

我想在邮件正文中发送图像。在这里,我正在加载基于数据库记录的图表。我通过以下代码将图表转换为字节:

string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);

现在,我想将此字节数组转换为 Image 并将该图像添加到邮件正文中。

这是我的发送邮件代码:

 MailMessage message = new MailMessage();
 string fromEmail = "domain.com";
 string fromPW = "12345";
 string toEmail = "abcde@gmail.com";     
 message.From = new MailAddress(fromEmail);
 message.To.Add(toEmail);
 message.Subject = "Chart Mail";
 message.Body = "Hi Team";
 message.IsBodyHtml = true;
 message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
 SmtpClient smtpClient = new SmtpClient("domain.com", 1234);
 smtpClient.EnableSsl = false;
 smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
 smtpClient.UseDefaultCredentials = false;
 smtpClient.Credentials = new NetworkCredential(fromEmail, fromPW);
 smtpClient.Send(message.From.ToString(), message.To.ToString(), message.Subject, message.Body);

在上面的代码中,我想将字节转换为图像,需要在邮件正文中发送。请提出建议。

【问题讨论】:

  • 我不确定如何使用内存中的图像,所以我不会发布答案,但如果文件存在于光盘上,您可以很容易地使用内联附件。我自己使用了这个确切的代码,并且可以确认它运行良好stackoverflow.com/questions/2317012/…
  • 这里,我根据数据库记录动态加载图表,并将图表转换为字节。光盘中不存在该文件。
  • 我知道,我说过这就是我不发布答案的原因。由于有很多关于如何从字节数组中获取图像的指南,我希望你自己做一些研究。此外,正如 Nemmy 所说,构造函数接受一个内存流,因此您可以直接使用它。
  • 是的。我正在这样做..

标签: c# asp.net image email byte


【解决方案1】:

无需将图像转换为字节。 你所要做的就是:

string attachmentPath = Environment.CurrentDirectory + @"\test.png";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);

message.Attachments.Add(inline);

这将在“内联”布局中显示消息,而不仅仅是附加图像

【讨论】:

  • 这里,我根据数据库记录动态加载图表,并将图表转换为字节。
  • Attachment 构造函数还可以得到一个 memoryStream,你可以从你的 byteArray 中得到它。
猜你喜欢
  • 2011-01-19
  • 1970-01-01
  • 2014-09-28
  • 2011-07-20
  • 2017-02-09
  • 2013-01-05
  • 2016-05-25
  • 2011-07-19
  • 2014-12-01
相关资源
最近更新 更多