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

时间:2013-11-11 16:11:27

标签: c# image visual-studio-2010

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

Bitmap myImage = new Bitmap(Resources.Image);

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

这是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>

非常感谢任何帮助谢谢!

编辑:这是整个代码块。我认为我接近它,只是缺乏经验阻碍这里:)我尝试将其转换为像我所说的那个让我更远的字节。仍然没有渲染图像。这里有些东西我做得不对。非常感谢大家帮助大家!这是代码(图像所需的HTML在字符串体的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("noreply@stormcopper.com");



            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:busbar@stormcopper.com'>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);

        }

5 个答案:

答案 0 :(得分:14)

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

这里是我之前使用过的一些代码很好的代码。我希望这会给你一些指导:

创建AlternateView

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

创建链接资源:

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

//将其添加到备用视图

av.LinkedResources.Add(logo);

//最后,在邮件中添加备用视图:

msg.AlternateView.Add(av);

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

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

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

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

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

<强>更新

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

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("xxx@example.com");


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

//然后发送消息!

答案 1 :(得分:0)

一个选项是将图像放在一个主机中,并在src中放置url,如“src ='http://www.host/myImage.jpg'” 这样您就不必在每封邮件中加载图像,而且更灵活。

答案 2 :(得分:0)

如果它对任何人都有帮助,这里有一个基于Ahmed ilyas' very useful answer的版本,它将实际的Bitmap传递给内存流,并包含在IDisposable块中实现using的各种对象 -

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);
            }
        }
    }

答案 3 :(得分:0)

我知道这是一篇过时的文章,但是如果有人仍然按此来寻找答案(就像我一样),那么我的答案就会更简单。

您可以使用LinkedResource对象的简单重载,该对象直接将文件路径作为参数。因此,无需将映像显式加载到内存流中。当然,此示例假设您有权访问磁盘上的映像-

这是为我工作的完整功能代码-

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;
    }
}

答案 4 :(得分:-2)

您不应将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>

以下内容:

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>