我想在我的电子邮件中嵌入图片

时间:2018-05-22 13:49:30

标签: c# css image email embed

我一直在尝试许多不同的东西,但我似乎无法弄清楚如何在我的代码中嵌入图像。我的计划是在字符串正文中发送带有图像的邮件。图像保存在内容文件夹中。

mm.Subject = "CompanyName ";
string body = "Dear " + CustomerMasterObj.CustomerName + ", \n";
                    body += "\n";
                    body += "\n";    
                    body += EmailTemplateObj.EmailMsg;
                    body += "\n";
                    body += Userurl;
                    body += "\n";
                    body += "Thank you in advance. \n";
                    body += "\n";
                    body += " Yours sincerely, \n";
                    body += "\n";
                    body += "John Doe \n";
                    mm.Body = body;    
                    mm.IsBodyHtml = false;

2 个答案:

答案 0 :(得分:0)

您可以使用HTML添加<img>代码,但这意味着将您的图片转换为base64或托管它:

这是一些实现的伪代码:

MailMessage mm = new MailMessage
   {
     IsBodyHtml = true,
     Subject = "CompanyName",
   };
string body = "HTML OPENING TAG .... YOUR CONTENT";
body += "<img src=\"data:image/png;base64," + Convert.ToBase64String(File.ReadAllBytes("path")) + "\" alt=\"myimage\" />";
body += "MORE HTML + HTML CLOSING TAG";
mm.Body = body;

答案 1 :(得分:0)

尝试使用LinkedResource对象,因为在某些情况下,没有LinkedResource图像的移动电子邮件应用程序没有出现给消息的接收者。

using System;
using System.IO;
using System.Net.Mail;

namespace PayneInMyButt
{
    public class EmailImage
    {
        public void DemoForImage()
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress("TODO");
                mail.To.Add("TODO");
                mail.Subject = "This is an email";

                AlternateView PlainMessage = AlternateView.CreateAlternateViewFromString("Hello, plain text", null, 
                    "text/plain");

                AlternateView HtmlMessage = AlternateView.CreateAlternateViewFromString(
                    "This is an automated email, please do not respond<br><br>This is a test <br>" + 
                    "<span style=\"font-weight: bold; padding-left: 20px;padding-right:5px\">Some bold text</span>" + 
                    "Non bold<br><span style=\"font-weight: bold; padding-left: 5px;padding-right:5px\">Second line</span>" + 
                    "This is Kate below<br><span style=\"font-weight: bold; padding-left: 70px;padding-right:5px\">" + 
                    "<img src=cid:Image1>", null, "text/html");

                LinkedResource Logo = new LinkedResource(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, 
                    "LogoImage.jpg"), 
                    "image/jpeg");

                Logo.ContentId = "Image1";

                mail.AlternateViews.Add(PlainMessage);
                mail.AlternateViews.Add(HtmlMessage);
                using (SmtpClient smtp = new SmtpClient("TODO"))
                {
                    smtp.Send(mail);
                }
            }
        }
    }
}