3

I followed this guide to try and embed 2 images on Emails this is my code written in C# for a console application: the ExecuteSendMailEx procedure:

 public void ExecuteSendMailEx(AccesBase accesBase, string From, string Subjet, bool Format, string EmailLogoHeader, string EmailLogoFooter, string ReplyTo, string ReturnPath, string BodyHtml, string BodyText, string Destinataire, string IdLangage, string CopieCachee, string PJ, string SMTP, string SMTPPORT, string SMTPLOGIN, string SMTPPWD, ref int RTN)
        {
            try
            {
                Log.Information("ENVOI_Constructor ExecuteSendMailEx has begun");
                var email = new MimeMessage();
                email.From.Add(MailboxAddress.Parse(From));
                email.To.Add(MailboxAddress.Parse(Destinataire));
                email.ReplyTo.Add(MailboxAddress.Parse(ReplyTo));
                if (!string.IsNullOrEmpty(CopieCachee))
                    email.Bcc.Add(MailboxAddress.Parse(CopieCachee));
                email.Subject = Subjet;
                email.Sender = (MailboxAddress.Parse(SMTPLOGIN));

                

                var currentDirectory = Directory.GetCurrentDirectory();
                var parentDirectory = Directory.GetParent(currentDirectory).FullName;
                var filesDirectory = parentDirectory + "\\Files";

                var builder = new BodyBuilder();
                if (EmailLogoHeader != "" && EmailLogoFooter != "")
                {
                    var imageHead = builder.LinkedResources.Add(filesDirectory + "\\" + EmailLogoHeader);
                    imageHead.ContentId = MimeUtils.GenerateMessageId();
                    var imageFoot = builder.LinkedResources.Add(filesDirectory + "\\" + EmailLogoFooter);

                    imageFoot.ContentId = MimeUtils.GenerateMessageId();
                    builder.HtmlBody = string.Format(@"<img src='cid:{0}'><br>{1}<br><img src='cid:{2} '>", imageHead.ContentId, BodyHtml, imageFoot.ContentId);
                }
                else if (EmailLogoFooter != "" && EmailLogoHeader == "")
                {
                    var imageFoot = builder.LinkedResources.Add(filesDirectory + "\\" + EmailLogoFooter);

                    imageFoot.ContentId = MimeUtils.GenerateMessageId();
                    builder.HtmlBody = string.Format(@"{0}<br><img src='cid={1}'>", BodyHtml, imageFoot.ContentId);
                }
                else if (EmailLogoHeader != "" && EmailLogoFooter == "")
                {
                    var imageHead = builder.LinkedResources.Add(filesDirectory+"\\" + EmailLogoHeader);
                    imageHead.ContentId = MimeUtils.GenerateMessageId();
                    builder.HtmlBody = string.Format(@"<img src='cid:{0}'><br>{1}", imageHead.ContentId, BodyHtml);
                }
                else
                    builder.HtmlBody = BodyHtml;

        
                builder.TextBody = BodyText ;
               
                if (Format == false)
                {
                    builder.Attachments.Add(addImage(filesDirectory + EmailLogoHeader));
                    builder.Attachments.Add(addImage(filesDirectory + EmailLogoFooter));
                }
                email.Body = Format == false ? new TextPart(TextFormat.Text) { Text = builder.TextBody } : new TextPart(TextFormat.Html){ Text= builder.HtmlBody };

                // send email
                var smtp = new MailKit.Net.Smtp.SmtpClient();
                smtp.Connect(SMTP, Int32.Parse(SMTPPORT), SecureSocketOptions.StartTls);
                smtp.Authenticate(SMTPLOGIN, SMTPPWD);
                smtp.Send(email);
                smtp.Disconnect(true);

                
            }
            catch (Exception ex) { Log.Error(ex.Message + " : " + ex.InnerException + " - ENVOI_Constructor: ExecuteSendMailEx Method"); }

           
        }

obviously, my first lines of the code are:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Web;
using TP;
using System.Net;
using System.Net.Mail;
using MimeKit;
using MimeKit.Text;
using MailKit.Net.Smtp;
using MailKit.Security;
using Serilog;
using System.Drawing;
using System.IO;
using MimeKit.Utils;

expected behavior: I tried everything to embed images to Emails sent with MailKit, but they always come out as actual situation all variables contain correct values like SMTP hosting the Exchange server address or SMTPPORT containing the port, every variable is named like its meaning, the EmailHeaderLogo & EmailFooterLogo contain the pathes like Mail\image.jpg, I navigated to the parent folder because the files are on the parent folder and inside the path that exist on the variable, sorry that the code may seem French, I'm not french but where I'm working is a french international company, if you want any additional information, don't hesitate to ask me, and thank you

bargo
  • 57
  • 9

1 Answers1

5

The problem is that you are setting the message body incorrectly.

Replace the following line:

email.Body = Format == false ? new TextPart(TextFormat.Text) { Text = builder.TextBody } : new TextPart(TextFormat.Html){ Text= builder.HtmlBody };

with this:

email.Body = builder.ToMessageBody();

I don't understand Format is supposed to do, but it looks like if Format is false, then you want only plain-text?

If so, you'll want to change your code to the following:

public void ExecuteSendMailEx(AccesBase accesBase, string From, string Subjet, bool Format, string EmailLogoHeader, string EmailLogoFooter, string ReplyTo, string ReturnPath, string BodyHtml, string BodyText, string Destinataire, string IdLangage, string CopieCachee, string PJ, string SMTP, string SMTPPORT, string SMTPLOGIN, string SMTPPWD, ref int RTN)
{
    try
    {
        Log.Information("ENVOI_Constructor ExecuteSendMailEx has begun");
        var email = new MimeMessage();
        email.From.Add(MailboxAddress.Parse(From));
        email.To.Add(MailboxAddress.Parse(Destinataire));
        email.ReplyTo.Add(MailboxAddress.Parse(ReplyTo));
        if (!string.IsNullOrEmpty(CopieCachee))
            email.Bcc.Add(MailboxAddress.Parse(CopieCachee));
        email.Subject = Subjet;
        email.Sender = (MailboxAddress.Parse(SMTPLOGIN));

        var currentDirectory = Directory.GetCurrentDirectory();
        var parentDirectory = Directory.GetParent(currentDirectory).FullName;
        var filesDirectory = Path.Combine(parentDirectory, "Files");

        var builder = new BodyBuilder();
        if (Format)
        {
            // If we have any headers or footers, inject those into the HTML body
            if (!string.IsNullOrEmpty(EmailLogoHeader) && !string.IsNullOrEmpty(EmailLogoFooter))
            {
                var imageHead = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoHeader));
                imageHead.ContentId = MimeUtils.GenerateMessageId();
                var imageFoot = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoFooter));

                imageFoot.ContentId = MimeUtils.GenerateMessageId();
                builder.HtmlBody = string.Format(@"<img src='cid:{0}'><br>{1}<br><img src='cid:{2} '>", imageHead.ContentId, BodyHtml, imageFoot.ContentId);
            }
            else if (!string.IsNullOrEmpty(EmailLogoFooter))
            {
                var imageFoot = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoFooter));

                imageFoot.ContentId = MimeUtils.GenerateMessageId();
                builder.HtmlBody = string.Format(@"{0}<br><img src='cid={1}'>", BodyHtml, imageFoot.ContentId);
            }
            else if (!string.IsNullOrEmpty(EmailLogoHeader))
            {
                var imageHead = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoHeader));
                imageHead.ContentId = MimeUtils.GenerateMessageId();
                builder.HtmlBody = string.Format(@"<img src='cid:{0}'><br>{1}", imageHead.ContentId, BodyHtml);
            }
            else
            {
                builder.HtmlBody = BodyHtml;
            }
        }
        else
        {
            // No HTML body is desired, so just add the header and footer images as attachments instead.
            if (!string.IsNullOrEmpty(EmailLogoHeader))
                builder.Attachments.Add(Path.Combine(filesDirectory, EmailLogoHeader));

            if (!string.IsNullOrEmpty(EmailLogoFooter))
                builder.Attachments.Add(Path.Combine(filesDirectory, EmailLogoFooter));
        }

        builder.TextBody = BodyText;

        email.Body = builder.ToMessageBody();

        // send email
        using (var smtp = new MailKit.Net.Smtp.SmtpClient())
        {
            smtp.Connect(SMTP, Int32.Parse(SMTPPORT), SecureSocketOptions.StartTls);
            smtp.Authenticate(SMTPLOGIN, SMTPPWD);
            smtp.Send(email);
            smtp.Disconnect(true);
        }
    }
    catch (Exception ex)
    {
        Log.Error(ex.Message + " : " + ex.InnerException + " - ENVOI_Constructor: ExecuteSendMailEx Method");
    }
}

Note: I took the liberty of changing your code to use string.IsNullOrEmpty() instead of doing a direct comparison with "" as well as fixing your code to use Path.Combine(). You should really get into the habit of using Path.Combine(), especially, since it will help make your code portable to non-Windows platforms if you ever want to run your code on .NET Core (where it may run on a Linux or Mac).

jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • hello and thanks for the help, yes, Format is bool, it says if the Email will be sent as a HTML text or as a plain text as for using C# best practices like the keyword `using`, the code was copied from an old ASP.NET WebForms site that didn't support any new C# implementation – bargo Aug 20 '21 at 15:25