I am interested in adding an image to my email communications

I have been experimenting with various methods, but I am struggling to figure out how to insert an image in my code. My goal is to include an image in the body of emails that are being sent out. The image itself is stored in the content folder.

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;

Answer №1

If you're looking to embed an image using HTML in your email, one option is to include the <img> tag after converting the image to base64 or hosting it:

Below is a sample pseudo-code snippet demonstrating how this can be done:

MailMessage message = new MailMessage
   {
     IsBodyHtml = true,
     Subject = "YourSubjectHere",
   };
string content = "START OF HTML .... YOUR CONTENT";
content += "<img src=\"data:image/png;base64," + Convert.ToBase64String(File.ReadAllBytes("path/to/image")) + "\" alt=\"image\" />";
content += "ADDITIONAL HTML + END OF HTML TAG";
message.Body = content;

Answer №2

To ensure images appear properly in mobile email applications, the following code snippet utilizes a LinkedResource object. Without using LinkedResource, images may not display correctly for the message recipient.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adaptable Design - Concealing Facebook Page Plugin at Specific Screen Widths

Can someone help me figure out how to hide the Facebook page plugin on my website? I tried using CSS but it doesn't seem to be working. Here is the code snippet: @media only screen and (max-width:800px){ .fb-page{ visibility: hidden; } This is t ...

What is causing the compatibility issue between Ant Design V5 styles and NextJS?

Description In my NextJS project, I am using the Ant Design V5 framework with multiple pages. However, I am facing an issue where the styles are only working correctly on one page and not being applied properly on other pages. Despite referring to the off ...

The 'ZipFile' namespace or type was not located

When attempting to use the code snippet using(ZipFile zip = new ZipFile()), I encountered the error message stating "the type or namespace 'ZipFile' could not be found." using(ZipFile zip = new ZipFile()) I have attempted to resolve this issue ...

Error encountered in ThreadPool when queuing UserWorkItem on the target with HttpContext

There is a challenge with a class that invokes a method but forgets about it afterwards. The issue arises when the called method contains an HttpContext and results in a NullReferenceException being thrown. It seems that using Httpcontext within the Threa ...

Using IndexOf with the Builders filter in MongoDB using C#

I need help with filtering a collection in this way Builders<myClass>.Filter.Where(d => d.Name.IndexOf(".") > length) However, I'm encountering the following error : System.InvalidOperationException: {document}{Name}.IndexOf(".") is n ...

How can I line up elements in different divs when the width is adjusting based on the window size?

Trying to align a search input and a result element in separate containers when the window size changes. Looking for a solution without using Javascript. One window size: https://i.sstatic.net/LiQtY.png A smaller window: https://i.sstatic.net/dgj4I.png C ...

Storing text from a text box in an XML file

My ASP.NET WebForm consists of 1 button and 4 textboxes. Each time the page loads, the code below reads data from an XML file and displays it in the textboxes: private void PutWhatWasBefore() { var xml = XDocument.Load(@"C:\Settings.xml"); F ...

What is the best way to update the style of a class in Bootstrap when working offline with a CDN?

Is it possible to customize the style of a predefined class in Bootstrap when using it through a CDN? For instance, if I am using a navigation menu, how can I modify its styling that is specified in the navigation class? ...

Google BigQuery does not support loading CSV files

Recently, I developed a program that automates the process of extracting schema from a MySQL Server table, creating a new table based on that schema, and importing data rows from a CSV file stored in Google Cloud Storage. The following code snippet is use ...

Maintain the text layout when copying and pasting from the Angular Application

After noticing that copying and pasting text from an Angular Application to a text editor like Microsoft Word results in losing the original format, I decided to investigate further. An example I used was the angular material website: https://material.ang ...

Centralized logo and slogan with Bootstrap 4 in navigation collapse

I am currently working on a Bootstrap 4 project that involves a navigation bar with a centered logo and tagline, along with links positioned to the left and right. While the setup is close to what I want, my ideal scenario would be for the logo to remain c ...

Steps for populating the TextBox with the current date

Greetings to everyone! I hope you are all doing well. I am new to .net development and working on a project that requires collecting daily information about the user. My issue is that I want the date textbox to automatically populate with the current date. ...

An error has been detected in the event log: "An unexpected exception has been encountered."

I have encountered a warning in the event log while using Visual Studio 2005 and IIS 6.0. This is a new exception for me and I am unsure how to handle it. Any suggestions on how to prevent this exception warning from occurring again would be greatly apprec ...

What is the best way to determine the correct file name number based on the position of trackBar1 after movement?

I currently have trackBar1 in the form1 constructor where I am retrieving all the files from a specific directory: DirectoryInfo dir1 = new DirectoryInfo(radar_images_download_directory); file_info_mouse_wheel = dir1.GetFiles("*.gif"); In addition, I als ...

Using Selenium C# Webdriver to ensure completion of all actions before closing the session

In my project, I am utilizing Selenium Web Driver version 2.48.2. The issue I am facing involves the need to ensure that the final URL is completely loaded before capturing a screenshot and closing the browser and driver. During debugging, all of my meth ...

Toggle the visibility of an element by clicking a button

I have a table structured as follows: <tr> <td class="title">Title</td> <td class="body">Body</td> <td class="any">Any text</td> </tr> <tr> <td class="title">Title</td> ...

Is it possible to create a custom dropdown in react with both radio buttons and checkboxes?

I've been searching for a custom third-party library to meet a specific need I have. Here's a snapshot of the dropdown in question. I looked into https://www.npmjs.com/package/multiselect-react-dropdown but it doesn't cover this particular s ...

Align images at the center of a division using the Bootstrap framework

I'm facing an issue with centering social network icons under a div in my login form while keeping it responsive. Can someone please assist me with this problem? Please help me!!. .row { background: #f8f9fa; margin-top: 20px; } .col { bor ...

Avoiding the <br> tag in list items with TinyMCE

I am currently using tinyMCE and I needed to enable the "force_br_newlines: true" option. Without this setting, if I press the "Enter" key twice and check the source code, I only see one <br> tag. However, when I set the option to TRUE, it creates a ...

Difficulties encountered while trying to set up a multi-level list for a mobile

Trying out a tutorial to create a mobile dropdown menu. Encountering an issue when adding new lists inside a previous tag affects the functionality of the dropdown menu. Attempted to adjust the CSS without success. All the lists are displayed without req ...