0

I want to send an image of a page output (html + css) as an e-mail. I wrote the code below for this, e-mail is sent but the image cannot be displayed in body. where am I doing wrong? can you please help?

public ActionResult Index()
{
    ViewBag.Title = "Home Page";
    MailMessage ms = new MailMessage("********@outlook.com", "******@outlook.com");
    ms.Subject = "Hello";

    var webClient = new WebClient();
    byte[] imageBytes = webClient.DownloadData("https://www.google.com/");

    ms.Body = @"<img src=""data:image/png;base64," + Convert.ToBase64String(imageBytes, 0, imageBytes.Length) + @""" alt =""Google"" width=""500"" height=""600"">";

    ms.IsBodyHtml = true;

    SmtpClient smtp = new SmtpClient("smtp.office365.com", 587);
    smtp.EnableSsl = true;
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

    System.Net.NetworkCredential nc = new System.Net.NetworkCredential("*****@outlook.com", "********");
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = nc;

    smtp.Send(ms);
    return View();
}
sdm
  • 33
  • 4
  • Reading your code, not sure that imageBytes really contains bytes corresponding to an image. –  Jul 05 '21 at 13:40
  • Actually I am not sure I copied this part, may be I need a third party for this converting – sdm Jul 05 '21 at 13:43
  • You have too many escape chars like """ I would handle this in Helper/Extension method so something like . This would also create and pass out the full data::xxx,xxx string with all data required. Also best way to check what is happening is view the source of your email from the email client. – AliK Jul 05 '21 at 14:02
  • So written, webClient.DownloadData("https://www.google.com/") downloads the HTML content of the main page of Google. Test your code with a local image : byte[] imageBytes = System.IO.File.ReadAllBytes(@"c:\...\myimage.png"); –  Jul 05 '21 at 14:02
  • I have tried with local image and result is same, image can not be displayed in email body @GuyatMercator – sdm Jul 05 '21 at 14:38
  • I've used such a code in similar circumstances: string base64String = Convert.ToBase64String(imageBytes, Base64FormattingOptions.None); string imgElement = string.Format("", base64String); –  Jul 05 '21 at 14:42
  • Try adding: ms.BodyFormat = MailFormat.Html; –  Jul 05 '21 at 14:48
  • I have configured the html body setting with "ms.IsBodyHtml = true;". I tried another html content without image and I saw that render is fine. I also tried the above code, but unfortunately the result is the same. Do you think I need to use a third party to convert the image of a web page? @GuyatMercator – sdm Jul 05 '21 at 16:25
  • I think you have to use what AliK said: to check what is happening is view the source of your email from the email client. –  Jul 05 '21 at 17:05

0 Answers0