Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending MHT file using C# Mail Message

Tags:

c#

Has anyone got any sample code to send MHT using SmtpClient and MailMessage in C#?

I have found tantalising references to using Alternate Views but I cannot figure out how to make this work with my SSRS generated MHT.

If anyone has any working code they are willing to share I would be greatly appreciative.

like image 779
TheEdge Avatar asked Oct 19 '25 23:10

TheEdge


1 Answers

So it appears that .NET MailMessage does not support this out of the box. I have found a couple of approaches that can be used with varying degrees of success.

MHTML -> HTML Decoder

David Benko wrote https://github.com/DavidBenko/MHTML-to-HTML-Decoding-in-C-Sharp/blob/master/MHTMLParser.cs and while it works, I was unable to make the images appear when I viewed the resulting email. The HTML looked right, it just did not work in Outlook 2010.

Convert MimeKit MimeMessage to .NET Mail Message

As Jeffrey points out this is a start https://github.com/jstedfast/MimeKit/issues/140. I had problems again with the images not being displayed in the resulting message.

Use MimeKit & MailKit

I ended up using https://github.com/jstedfast/MimeKit to do the job. This can be achieved as follows:

   MimeMessage messageMimeKit = MimeMessage.Load(Request.MapPath("~/Blah/378921.mht"));

   messageMimeKit.From.Add(new MailboxAddress("Dev", "[email protected]"));
   messageMimeKit.To.Add(new MailboxAddress("Homer", "[email protected]"));
   messageMimeKit.Subject = "Another subject line";
   using (var client = new MailKit.Net.Smtp.SmtpClient()) 
   {
      client.Connect("smtp.gmail.com", 465, true);
      client.Authenticate("[email protected]", "*****");
      client.Send(messageMimeKit);
      client.Disconnect(true);
   }
like image 161
TheEdge Avatar answered Oct 21 '25 15:10

TheEdge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!