C# 将图像添加到 System.Net.Mail 消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19910871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:06:09  来源:igfitidea点击:

Adding Image to System.Net.Mail Message

c#imagevisual-studio-2010

提问by lazoDev

I have some images stored in the Resources.resx file in my solution. I would like to use these images in my email. I have loaded the image into a variable:

我的解决方案的 Resources.resx 文件中存储了一些图像。我想在我的电子邮件中使用这些图像。我已将图像加载到变量中:

Bitmap myImage = new Bitmap(Resources.Image);

and now I want to put it in the HTML in the AlternateView string I am using to create the HTML email. Just need some help.

现在我想把它放在我用来创建 HTML 电子邮件的 AlternateView 字符串中的 HTML 中。只是需要一些帮助。

Here is the HTML string(partial):

这是 HTML 字符串(部分):

 body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src='" + myImage + "' width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div>

Any help would be greatly appreciated Thanks!

任何帮助将不胜感激谢谢!

EDIT: Here is the entire Code block. I think I am close to getting it, just inexperience getting in the way here :) I tried converting it into a Byte like suggested which got me farther. Still not rendering the image. There is something here I am not doing right. Thank you so much for all of you help everyone! Here is the code (the HTML I need for the image is in the 3 line of the string body = code):

编辑:这是整个代码块。我想我快要得到它了,只是缺乏经验阻碍了 :) 我试着把它转换成一个像建议的字节,这让我走得更远。仍然没有渲染图像。这里有些事情我做得不对。非常感谢大家对大家的帮助!这是代码(我需要的图像的 HTML 在字符串 body = code 的第 3 行):

 if (emailTo != null)
        {

            Bitmap myImage = new Bitmap(Resources.comcastHeader);
            ImageConverter ic = new ImageConverter();
            Byte[] ba = (Byte[])ic.ConvertTo(myImage, typeof(Byte[]));
            MemoryStream image1 = new MemoryStream(ba);

            LinkedResource headerImage = new LinkedResource(image1, "image/jpeg");
            headerImage.ContentId = "companyLogo";


            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
            message.To.Add("" + emailTo + "");
            message.Subject = "" + customer + " Your order is being processed...";
            message.From = new System.Net.Mail.MailAddress("[email protected]");



            string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
            body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
            body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src=\"cid:companyLogo\" width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div><P>Hello " + customer + ",</P><P>Thank you for shopping at <a href='" + store + "'>" + store + "</A>.  Your order is being processed and will be shipped to you soon.  We would like to take this time to thank you for choosing Storm Copper Components, and we hope you are completely satisfied with your purchase. Please review your information and make sure all the information is correct.  If there are any errors in your order, please contact us immediately <A href='mailto:[email protected]'>here.</A></P>";               
            body += "<P><B>Here is your order information:</B></P>";
            body += "<H3>Contact Information</H3><TABLE><TR><TD><B>Name:</B> " + customer + "</TR></TD><TR><TD><B>Address:</B> " + street + " " + city + ", " + state + " " + zip + "</TR></TD><TR><TD><B>Email:</B> " + emailTo + "</TR></TD><TR><TD><B>Phone:</B> " + phone + "</TR></TD><TR><TD></TD></TR></TABLE>";
            body += "<H3>Products Ordered</H3><TABLE>" + productInformation + "</TABLE><BR /><BR />";
            body += "<H3>Pricing Information</H3><TABLE><TR><TD>Subtotal: $" + subTotal + "</TD></TR><TR><TD>Shipping: $" + shippingInfo + " </TD></TR><TR><TD>Tax: $" + taxInfo + "</TD></TR><TR><TD><B>Total:</B> $" + total + "</TD></TR><BR /></TABLE>";
            body += "<P>Thank you for shopping with us!</P><A href='stormcopper.com'>Storm Copper Components</A>";
            body += "<P><I>This is an Auto-Generated email sent by store copper.  Your email will not be sent to Storm Copper Components if you reply to this message.  If you need to change any information, or have any questions about your order, please contact us using the information provided in this email.</I></P></DIV></BODY></HTML>";



            ContentType mimeType = new System.Net.Mime.ContentType("text/html");

            AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);

            message.AlternateViews.Add(alternate);
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("########");
            smtp.Send(message);

        }

采纳答案by Ahmed ilyas

you need to add them in the email message as CID's/linked resources.

您需要将它们作为 CID/链接资源添加到电子邮件中。

here is some code I have used before which works nicely. I hope this gives you some guidance:

这是我之前使用过的一些代码,效果很好。我希望这能给你一些指导:

Create an AlternateView:

创建一个AlternateView

AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, isHTML ? System.Net.Mime.MediaTypeNames.Text.Html : System.Net.Mime.MediaTypeNames.Text.Plain)

Create a Linked Resource:

创建链接资源:

LinkedResource logo = new LinkedResource("SomeRandomValue", System.Net.Mime.MediaTypeNames.Image.Jpeg);
logo.ContentId = currentLinkedResource.Key;
logo.ContentType = new System.Net.Mime.ContentType("image/jpg");

// add it to the alternative view

// 将其添加到替代视图

av.LinkedResources.Add(logo);

// finally, add the alternative view to the message:

// 最后,将替代视图添加到消息中:

msg.AlternateView.Add(av);

here is some documentation to help you with what the AlternativeView and LinkedResources are and how it works:

这里有一些文档可以帮助您了解 AlternativeView 和 LinkedResources 是什么以及它是如何工作的:

http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.net.mail.linkedresource(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/ms144669(v=vs.110).aspx

http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/ system.net.mail.linkedresource(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/ms144669(v=vs.110).aspx

in the HTML itself, you need to do something like the following:

在 HTML 本身中,您需要执行以下操作:

"<img style=\"width: 157px; height: 60px;\" alt=\"blah blah\" title=\"my title here\" src=\"cid:{0}\" />";

notice the CID followed by a string format {0} - I then use this to replace it with a random value.

注意 CID 后跟字符串格式 {0} - 然后我使用它用随机值替换它。

UPDATE

更新

To go back and comment on the posters comments... here is the working solution for the poster:

要返回并评论海报评论......这是海报的工作解决方案:

string body = "blah blah blah... body goes here with the image tag: <img src=\"cid:companyLogo\" width="104" height="27" />";

byte[] reader = File.ReadAllBytes("E:\TestImage.jpg");
MemoryStream image1 = new MemoryStream(reader);
AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, System.Net.Mime.MediaTypeNames.Text.Html);

LinkedResource headerImage = new LinkedResource(image1, System.Net.Mime.MediaTypeNames.Image.Jpeg);
headerImage.ContentId = "companyLogo";
headerImage.ContentType = new ContentType("image/jpg");
av.LinkedResources.Add(headerImage);


System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.AlternateViews.Add(av);
message.To.Add(emailTo);
message.Subject = " Your order is being processed...";
message.From = new System.Net.Mail.MailAddress("[email protected]");


ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);

// then send message!

// 然后发送消息!

回答by Nacho

One option is put the image in one host, and in the src put the url, like this "src='http://www.host/myImage.jpg'" This way you do not have to load the image in each mail and would be more agile.

一种选择是将图像放在一个主机中,并在 src 中放入 url,就像这样“src=' http://www.host/myImage.jpg'” 这样您就不必在每封邮件中加载图像并且会更敏捷。

回答by Sudhakar Tillapudi

you should not assign the Bitmapobject to <img>tag as it expects the image path.
Replace this:

您不应将Bitmap对象分配给<img>标记,因为它需要图像路径。
替换这个:

body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src='" + myImage + "' width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div>

With following :

与以下:

body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src='" + Resources.Image+ "' width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div>

回答by Parrybird

If it helps anyone, here is a version based on Ahmed ilyas' very useful answer, which passes the actual Bitmap to the memory stream, and encloses the various objects which implement IDisposablein usingblocks -

如果它对任何人有帮助,这里有一个基于Ahmed ilyas 非常有用的答案的版本,它将实际位图传递给内存流,并包含IDisposableusing块中实现的各种对象-

public void SendMailExample(string emailAddressTo, string hexColour)
    {
        // Give the LinkedResource an ID which should be passed into the 'cid' of the <img> tag -
        var linkedResourceId = "mylogo";
        var sb = new StringBuilder("");
        sb.Append("<body><p>This is the HTML email body with img tag...<br /><br />");
        sb.Append($"<img src=\"cid:{linkedResourceId}\" width=\"100\" height=\"115.5\" alt=\"Logo\"/>");
        sb.Append("<p></body>");
        var emailBodyHtml = sb.ToString();
        var emailBodyPlain = "This is the plain text email body";

        using (var message = new MailMessage())
        using (var logoMemStream = new MemoryStream())
        using (var altViewHtml = AlternateView.CreateAlternateViewFromString(emailBodyHtml, null, System.Net.Mime.MediaTypeNames.Text.Html))
        using (var altViewPlainText = AlternateView.CreateAlternateViewFromString(emailBodyPlain, null, System.Net.Mime.MediaTypeNames.Text.Plain))
        using (var client = new System.Net.Mail.SmtpClient(_smtpServer)
        {
            Port = 25,
            DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            EnableSsl = false
        })
        {
            message.To.Add(emailAddressTo);
            message.From = new MailAddress(_emailAddressFrom);
            message.Subject = "This is the email subject";

            // Assume that GetLogo() just returns a Bitmap (for my particular problem I had to return a logo in a specified colour, hence the hexColour parameter!)
            Bitmap logoBitmap = GetLogo(hexColour);
            logoBitmap.Save(logoMemStream, System.Drawing.Imaging.ImageFormat.Png);
            logoMemStream.Position = 0;

            using (LinkedResource logoLinkedResource = new LinkedResource(logoMemStream))
            {
                logoLinkedResource.ContentId = linkedResourceId;
                logoLinkedResource.ContentType = new ContentType("image/png");
                altViewHtml.LinkedResources.Add(logoLinkedResource);
                message.AlternateViews.Add(altViewHtml);
                message.AlternateViews.Add(altViewPlainText);

                client.Send(message);
            }
        }
    }

回答by A. Varma

I know this is an old post, but if someone still hits this looking for an answer (like I did), then I have a simpler answer.

我知道这是一个旧帖子,但如果有人仍然点击这个寻找答案(就像我一样),那么我有一个更简单的答案。

You can use a simple overload of LinkedResource object that directly takes the file path as the parameter. So there is no need to explicitly load image into memory stream. Of course, this example assumes you have access to the image on the disk -

您可以使用直接以文件路径作为参数的 LinkedResource 对象的简单重载。所以没有必要显式地将图像加载到内存流中。当然,这个例子假设你可以访问磁盘上的图像 -

Here is the complete function code which worked for me -

这是对我有用的完整功能代码 -

public System.Net.Mail.AlternateView GetAlternateView(string MessageText, string LogoPath, bool bSilent)
{

    try
    {
        MessageText += "<br><img title='' alt='' src='cid:SystemEmail_HTMLLogoPath' />";               

        System.Net.Mail.AlternateView view = System.Net.Mail.AlternateView.CreateAlternateViewFromString(MessageText, null, "text/html");
        System.Net.Mail.LinkedResource linked = new System.Net.Mail.LinkedResource(HttpContext.Current.Request.PhysicalApplicationPath + LogoPath);
        linked.ContentId = "SystemEmail_HTMLLogoPath";
        view.LinkedResources.Add(linked);
        return view;
    }
    catch (Exception ex)
    {
        if (bSilent)
            return null;
        else
            throw ex;
    }
}