How to add image to email?

Cenk 1,001 Reputation points
2024-08-17T12:16:39.34+00:00

Hi,

In my e-commerce application, I am sending an order confirmation email to the customer. I am using a html template for this e-mail. I couldn't figure out how to display the logo and ordered product image in the e-mail.

Here is the html template:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Email Template for Order Confirmation Email</title>
    <!-- Start Common CSS -->
    <style type="text/css">
    #outlook a {{
            padding: 0;
        }}
        body {{
            width: 100% !important;
            -webkit-text-size-adjust: 100%;
            -ms-text-size-adjust: 100%;
            margin: 0;
            padding: 0;
            font-family: Helvetica, arial, sans-serif;
        }}
        .ExternalClass {{
            width: 100%;
        }}
            .ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font, .ExternalClass td, .ExternalClass div {{
                line-height: 100%;
            }}
        .backgroundTable {{
            margin: 0;
            padding: 0;
            width: 100% !important;
            line-height: 100% !important;
        }}
        .main-temp table {{
            border-collapse: collapse;
            mso-table-lspace: 0pt;
            mso-table-rspace: 0pt;
            font-family: Helvetica, arial, sans-serif;
        }}
            .main-temp table td {{
                border-collapse: collapse;
            }}
    </style>
    <!-- End Common CSS -->
</head>
<body>
    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="backgroundTable main-temp" style="background-color: #d5d5d5;">
        <tbody>
            <tr>
                <td>
                    <table width="650" align="center" cellpadding="15" cellspacing="0" border="0" class="devicewidth" style="background-color: #ffffff;">
                        <tbody>
                            <!-- Start header Section -->
                            <tr>
                                <td style="padding-top: 30px;">
                                    <table width="560" align="center" cellpadding="0" cellspacing="0" border="0" class="devicewidthinner" style="border-bottom: 1px solid #eeeeee; text-align: center;">
                                        <tbody>
                                            <tr>
                                                <td style="padding-bottom: 10px;">
                                                    <a href="http://localhost:7169/"><img src="images/logo.png" alt="Walk In Style" /></a>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="font-size: 14px; line-height: 18px; color: #666666;">
                                                    3828 Mall Road
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="font-size: 14px; line-height: 18px; color: #666666;">
                                                    123 Consectetur at ligula 10660
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="font-size: 14px; line-height: 18px; color: #666666;">
                                                    Phone: 010-020-0340 | Email:  info@company.com
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="font-size: 14px; line-height: 18px; color: #666666; padding-bottom: 25px;">
                                                    <strong>Order Number:</strong> --OrderId-- | <strong>Order Date:</strong> --OrderDate--
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                            <!-- End header Section -->
                            <!-- Start address Section -->
                            <tr>
                                <td style="padding-top: 0;">
                                    <table width="560" align="center" cellpadding="0" cellspacing="0" border="0" class="devicewidthinner" style="border-bottom: 1px solid #bbbbbb;">
                                        <tbody>
                                            <tr>
                                                <td style="width: 55%; font-size: 16px; font-weight: bold; color: #666666; padding-bottom: 5px;">
                                                    Delivery Adderss
                                                </td>
                                                <td style="width: 45%; font-size: 16px; font-weight: bold; color: #666666; padding-bottom: 5px;">
                                                    Billing Address
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="width: 55%; font-size: 14px; line-height: 18px; color: #666666;">
                                                    --Name--
                                                </td>
                                                <td style="width: 45%; font-size: 14px; line-height: 18px; color: #666666;">
                                                    --Name--
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="width: 55%; font-size: 14px; line-height: 18px; color: #666666;">
                                                    --Address--
                                                </td>
                                                <td style="width: 45%; font-size: 14px; line-height: 18px; color: #666666;">
                                                    --Address--
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="width: 55%; font-size: 14px; line-height: 18px; color: #666666; padding-bottom: 10px;">
                                                    --City--
                                                </td>
                                                <td style="width: 45%; font-size: 14px; line-height: 18px; color: #666666; padding-bottom: 10px;">
                                                    --City--
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                            <!-- End address Section -->
                            <!-- Start product Section -->
                            <!-- Start calculation Section -->
                            <tr>
                                <td style="padding-top: 0;">
                                    <table width="560" align="center" cellpadding="0" cellspacing="0" border="0" class="devicewidthinner" style="border-bottom: 1px solid #bbbbbb; margin-top: -5px;">
                                        <tbody>
                                            <tr>
                                                <td rowspan="5" style="width: 55%;"></td>
                                                <td style="font-size: 14px; line-height: 18px; color: #666666;">
                                                    Sub-Total:
                                                </td>
                                                <td style="font-size: 14px; line-height: 18px; color: #666666; width: 130px; text-align: right;">
                                                    --SubTotal--
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="font-size: 14px; line-height: 18px; color: #666666; padding-bottom: 10px; border-bottom: 1px solid #eeeeee;">
                                                    Shipping Fee:
                                                </td>
                                                <td style="font-size: 14px; line-height: 18px; color: #666666; padding-bottom: 10px; border-bottom: 1px solid #eeeeee; text-align: right;">
                                                    $5.00
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="font-size: 14px; font-weight: bold; line-height: 18px; color: #666666; padding-top: 10px;">
                                                    Order Total
                                                </td>
                                                <td style="font-size: 14px; font-weight: bold; line-height: 18px; color: #666666; padding-top: 10px; text-align: right;">
                                                    --Total--
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>


Here is the e-mail method:

private async Task SendOrderConfirmationEmail(OrderHeaderDTO orderHeaderDTO)
{
    try
    {
        // Get the order for details in the template
        var orders = await _orderRepository.GetOrdersByUser(orderHeaderDTO.UserId);
        var order = orders.Where(o => o.OrderHeader.Id == orderHeaderDTO.Id).FirstOrDefault();
        // Construct the path to the file
        var pathToFile = Path.Combine("Templates", "EmailTemplate", "Confirmation_EmailTemplate.html");
        // Check if the file exists
        if (!System.IO.File.Exists(pathToFile))
        {
            throw new FileNotFoundException("The email template file was not found.", pathToFile);
        }
        var builder = new BodyBuilder();
        using (var SourceReader = System.IO.File.OpenText(pathToFile))
        {
            builder.HtmlBody = SourceReader.ReadToEnd();
        }
        var tableRows = new StringBuilder();
        foreach (var detail in order.OrderDetails)
        {
            tableRows.Append($@"
            <tr>
                <td style='padding-top: 0;'>
                    <table width='560' align='center' cellpadding='0' cellspacing='0' border='0' class='devicewidthinner' style='border-bottom: 1px solid #eeeeee;'>
                        <tbody>
                            <tr>
                                <td rowspan='4' style='padding-right: 10px; padding-bottom: 10px;'>
                                    <img style='height: 80px;' src='{detail.Product?.ImageUrls.FirstOrDefault()}' alt='Product Image' />
                                </td>
                                <td colspan='2' style='font-size: 14px; font-weight: bold; color: #666666; padding-bottom: 5px;'>
                                    {detail.ProductName}
                                </td>
                            </tr>
                            <tr>
                                <td style='font-size: 14px; line-height: 18px; color: #757575; width: 440px;'>
                                    Quantity: {detail.Count}
                                </td>
                                <td style='width: 130px;'></td>
                            </tr>
                            <tr>
                                <td style='font-size: 14px; line-height: 18px; color: #757575;'>
                                    Color: {detail.Product?.Color}
                                </td>
                                <td style='font-size: 14px; line-height: 18px; color: #757575; text-align: right;'>
                                    {detail.Price.ToString("C", CultureInfo.InvariantCulture)} Per Unit
                                </td>
                            </tr>
                            <tr>
                                <td style='font-size: 14px; line-height: 18px; color: #757575; padding-bottom: 10px;'>
                                    Size: {detail.Size}
                                </td>
                                <td style='font-size: 14px; line-height: 18px; color: #757575; text-align: right; padding-bottom: 10px;'>
                                    <b style='color: #666666;'>{(detail.Price * detail.Count).ToString("C", CultureInfo.InvariantCulture)}</b> Total
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>");
        }
        // Replace the placeholder in the HTML template with the generated tableRows
        builder.HtmlBody = builder.HtmlBody.Replace("<!-- Start product Section -->", tableRows.ToString());
        builder.HtmlBody = builder.HtmlBody.Replace("--OrderId--", orderHeaderDTO.Id.ToString());
        builder.HtmlBody = builder.HtmlBody.Replace("--OrderDate--", orderHeaderDTO.OrderDate.ToString());
        builder.HtmlBody = builder.HtmlBody.Replace("--Name--", orderHeaderDTO.Name);
        builder.HtmlBody = builder.HtmlBody.Replace("--Address--", orderHeaderDTO.StreetAddress);
        builder.HtmlBody = builder.HtmlBody.Replace("--City--", orderHeaderDTO.City);
        builder.HtmlBody = builder.HtmlBody.Replace("--SubTotal--", orderHeaderDTO.OrderTotal.ToString("C", CultureInfo.InvariantCulture));
        builder.HtmlBody = builder.HtmlBody.Replace("--Total--", (orderHeaderDTO.OrderTotal
            + 5).ToString("C", CultureInfo.InvariantCulture));
        // Send the email
        await _emailSender.SendEmailAsync(orderHeaderDTO.Email, "Order Confirmation", builder.HtmlBody);
    }
    catch (Exception e)
    {
        throw new Exception(e.Message);
    }
}
public async Task SendEmailAsync(string email, string subject, string htmlMessage)
{
    try
    {
        var emailToSend = new MimeMessage();
        emailToSend.From.Add(MailboxAddress.Parse("test@test.com"));
        emailToSend.To.Add(MailboxAddress.Parse(email));
        emailToSend.Subject = subject;
        emailToSend.Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = htmlMessage };
        //send email
        using var emailClient = new SmtpClient();
        await emailClient.ConnectAsync("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.StartTls);
        await emailClient.AuthenticateAsync("test@test.com", "test");
        await emailClient.SendAsync(emailToSend);
        await emailClient.DisconnectAsync(true);
    }
    catch (Exception)
    {
        throw;
    }
}

Hope you can help me.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,545 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,567 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,882 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. AgaveJoe 28,131 Reputation points
    2024-08-17T14:11:39.5933333+00:00

    I couldn't figure out how to display the logo and ordered product image in the e-mail.

    Set an image tag's src attribute to the URL where the logo image is hosted.

    https://www.w3schools.com/tags/tag_img.asp

    <img src="https://www.mydomain.com/images/logo.img" />
    

  2. Bruce (SqlWork.com) 64,816 Reputation points
    2024-08-17T15:32:52.7466667+00:00

    While you can use a source url, most email system will suppress loading the image. You can use a data url:

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs

    the other approach is to add the image as an attachment and use a content id in the image reference.

    https://sendgrid.com/en-us/blog/embedding-images-emails-facts


  3. Tiny Wang-MSFT 2,641 Reputation points Microsoft Vendor
    2024-08-19T08:30:12.41+00:00

    Hi Cenk, here's my test result, could you please help check it?

    //using MimeKit.Utils;
    //using MimeKit;
    //using MailKit.Net.Smtp;
    //using MailKit.Security;
    public class SendEmailModel : PageModel
    {
    	private readonly IWebHostEnvironment _env;
    	public SendEmailModel(IWebHostEnvironment webHostEnvironment)
    	{
    		_env = webHostEnvironment;
    	}
    	public async void OnGet()
    	{
    		string subject = "Test Email with HTML and Image";
    		//html template
    		string htmlContent = "<h1>Hello</h1><p>This is a test email with an embedded image.</p><img src=\"data:image/jpg;base64,{image_src}\" style=\"width:100px;height:100px\">";
    		//image path
    		string imagePath = Path.Combine(_env.WebRootPath, "images", "Image3.jpg");
    		//get image base64 string.
    		byte[] fileContent = System.IO.File.ReadAllBytes(imagePath);
    		string base64 = Convert.ToBase64String(fileContent);
    		// Create a new MimeMessage
    		var message = new MimeMessage();
    		message.From.Add(new MailboxAddress("Your Name", "sender-email@example.com"));
    		message.To.Add(new MailboxAddress("", "recipient@example.com"));
    		message.Subject = subject;
    		// Create the body builder
    		var bodyBuilder = new BodyBuilder();
    		// Set the HTML body
    		bodyBuilder.HtmlBody = htmlContent;
    		// Embed the image
    		var image = bodyBuilder.LinkedResources.Add(imagePath);
    		image.ContentId = MimeUtils.GenerateMessageId();
    		// Replace the image src in the HTML content with the base64 string
    		bodyBuilder.HtmlBody = bodyBuilder.HtmlBody.Replace("{image_src}", base64);
    		// Set the message body
    		message.Body = bodyBuilder.ToMessageBody();
    		// Configure the SMTP client
    		using var client = new SmtpClient();
    		//in this sample, I'm using outlook to send the email, you can change it to yours.
    		client.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);
    		client.Authenticate("sender-email@example.com", "your-password");
    		// Send the message
    		await client.SendAsync(message);
    		client.Disconnect(true);
    	}
    }
    
    
    

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Tiny Wang


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.