我很难将Properties.Resources中的图像嵌入到MailMessage中,目前图片没有显示在我收到的电子邮件中。
我已成功从目录位置嵌入图像,但如果图像来自内存/应用程序则更喜欢。
以下是我正在做的简化版本。
Bitmap b = new Bitmap(Properties.Resources.companyLogo);
MemoryStream logo = new MemoryStream();
b.Save(logo, ImageFormat.Jpeg);
MailMessage newEmail = new MailMessage(from, to);
newEmail.Subject = subject;
newEmail.IsBodyHtml = true;
LinkedResource footerImg = new LinkedResource(logo, "image/jpeg");
footerImg.ContentId = "companyLogo";
AlternateView foot= AlternateView.CreateAlternateViewFromString(body + "<p> <img src=cid:companyLogo /> </p>", null, "text/html");
foot.LinkedResources.Add(footerImg);
newEmail.AlternateViews.Add(foot);
SmtpClient server = new SmtpClient(host, port);
server.Send(newEmail);
答案 0 :(得分:25)
好的,我已经解决了这个问题。
我没有使用BitMap保存方法,而是将BitMap转换为Byte [],并为内存流提供了Byte []
不起作用:
b.Save(logo, ImageFormat.Jpeg);
做了工作:
Bitmap b = new Bitmap(Properties.Resources.companyLogo);
ImageConverter ic = new ImageConverter();
Byte [] ba = (Byte[]) ic.ConvertTo(b,typeof(Byte[]));
MemoryStream logo = new MemoryStream(ba);
我认为它与Bitmap.Save方法有关,在MSDN lib中它提到流必须有0的偏移量。
答案 1 :(得分:19)
Bitmap b = new Bitmap(Properties.Resources.companyLogo);
MemoryStream logo = new MemoryStream();
b.Save(logo, ImageFormat.Jpeg);
执行保存后,您必须“寻找”MemoryStream回到开始。
logo.Position = 0;
答案 2 :(得分:2)
您可以嵌入图像,而可以通过将其转换为base64来跳过使用资源的操作:
public static string BitmapToBase64(Bitmap b)
{
ImageConverter ic = new ImageConverter();
byte[] ba = (byte[])ic.ConvertTo(b, typeof(byte[]));
return Convert.ToBase64String(ba, 0, ba.Length);
}
并将其用作html image src:
string logoimage="<img src='data:image/png;base64," + BitmapToBase64(logo) + "'>";
请注意,转换为Base64会明显增加图像的大小。
答案 3 :(得分:1)
试试看:
http://www.eggheadcafe.com/community/aspnet/2/10219822/send-mail-with-atttached-image.aspx
从上面的链接:
static void EmbedImages()
{
var mail = new MailMessage();
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");
mail.Subject = "This is an email";
var plainView = AlternateView.CreateAlternateViewFromString(
"This is my plain text content, viewable by those clients that don't support html",
null, "text/plain");
var htmlView = AlternateView.CreateAlternateViewFromString(
"Here is an embedded image.<img src=cid:companylogo>",
null, "text/html");
LinkedResource logo = new LinkedResource( "c:\\temp\\logo.gif" );
logo.ContentId = "companylogo";
htmlView.LinkedResources.Add(logo);
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
var smtp = new SmtpClient("127.0.0.1"); //specify the mail server address
smtp.Send(mail);
}
答案 4 :(得分:0)
我没有在“资源”中添加“徽标”,而是将其直接添加到项目中,并将其设置为“嵌入式资源”。
然后使用System.Reflection.Assymbly我可以得到它(我直接假设)作为Stream:
var _assembly = Assembly.GetExecutingAssembly();
var _logoStream = _assembly.GetManifestResourceStream("[Project].[Filename].png");
var logo = new LinkedResource(_logoStream, "image/png");
logo.ContentId = "Logo";
html.LinkedResources.Add(logo);