How to convert RTF to HTML email with images and send using SmtpClient in C# and .NET


If you are looking also for a .Net solution to Create or Modify HTML documents, see our Document .Net.

Complete code

using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using SkiaSharp;
using System.Net.Mime;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            string rtfFile = Path.GetFullPath(@"..\..\..\Images.rtf");

            // 1. Convert RTF to HTML and place all images to list
            SautinSoft.RtfToHtml r = new SautinSoft.RtfToHtml();
            SautinSoft.RtfToHtml.HtmlFixedSaveOptions opt = new SautinSoft.RtfToHtml.HtmlFixedSaveOptions
            {
                EmbedImages = false,
                ImagesDirectoryPath = Path.GetFullPath(@"..\..\..\Images"),
                ImagesDirectorySrcPath = Path.GetFullPath(@"..\..\..\Images")
            };
            string[] imageList = Directory.GetFiles(@"..\..\..\Images");

            // 2. After launching this method we'll get our RTF document in HTML format
            string htmlFile = Path.GetFullPath(@"..\..\..\Result.html");
            r.Convert(rtfFile, htmlFile, opt);

            // 3. Create Smtp client
            string userName = "bobuser";
            string userPassword = "bobpassword";
            string host = "smtp.bobsite.com";
            int port = 587;

            SmtpClient client = new SmtpClient(host, port)
            {
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential(userName, userPassword)
            };

            // 4. Create HTML email
            string from = "bob@bobsite.com";
            string to = "john@johnsite.com";
            string subject = "This is a testing email from Bob to John using SmtpClient";

            MailMessage emailMessage = new MailMessage
            {
                From = new MailAddress(from),
                Body = "Testing email",
                IsBodyHtml = true,
                Subject = subject.Replace("\r\n", "")
            };

            emailMessage.To.Add(to);

            // 5. Attach images to email
            AlternateView altView = AlternateView.CreateAlternateViewFromString(htmlFile, null, "text/html");

            foreach (string imgPath in imageList)
            {
                using (var inputStream = File.OpenRead(imgPath))
                {
                    using (var skBitmap = SKBitmap.Decode(inputStream))
                    {
                        if (skBitmap != null)
                        {
                            var ms = new MemoryStream();
                            using (var skImage = SKImage.FromBitmap(skBitmap))
                            using (var data = skImage.Encode(SKEncodedImageFormat.Png, 100))
                            {
                                data.SaveTo(ms);
                            }

                            ms.Position = 0;

                            var lr = new LinkedResource(ms)
                            {
                                ContentType = new ContentType("image/png"),
                                ContentId = Guid.NewGuid().ToString()
                            };

                            altView.LinkedResources.Add(lr);
                        }
                    }
                }
            }
            emailMessage.AlternateViews.Add(altView);

            // 6. Send the message using email account

            //client.UseDefaultCredentials = false;

            // Some smtp servers doesn't require credentials, therefore
            // you may set: client.UseDefaultCredentials = false;
            // and remove the line: client.Credentials = new NetworkCredential(userName, userPassword);

            // In the real example in case of the correct host, uncomment the line below:
            //client.Send(emailMessage);
            Console.WriteLine("The message has been sent!");
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports SkiaSharp
Imports System.Net.Mime

Namespace Sample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			Dim rtfFile As String = Path.GetFullPath("..\..\..\Images.rtf")

			' 1. Convert RTF to HTML and place all images to list
			Dim r As New SautinSoft.RtfToHtml()
			Dim opt As New SautinSoft.RtfToHtml.HtmlFixedSaveOptions With {
				.EmbedImages = False,
				.ImagesDirectoryPath = Path.GetFullPath("..\..\..\Images"),
				.ImagesDirectorySrcPath = Path.GetFullPath("..\..\..\Images")
			}
			Dim imageList() As String = Directory.GetFiles("..\..\..\Images")

			' 2. After launching this method we'll get our RTF document in HTML format
			Dim htmlFile As String = Path.GetFullPath("..\..\..\Result.html")
			r.Convert(rtfFile, htmlFile, opt)

			' 3. Create Smtp client
			Dim userName As String = "bobuser"
			Dim userPassword As String = "bobpassword"
			Dim host As String = "smtp.bobsite.com"
			Dim port As Integer = 587

			Dim client As New SmtpClient(host, port) With {
				.EnableSsl = True,
				.DeliveryMethod = SmtpDeliveryMethod.Network,
				.Credentials = New NetworkCredential(userName, userPassword)
			}

			' 4. Create HTML email
			Dim from As String = "bob@bobsite.com"
			Dim [to] As String = "john@johnsite.com"
			Dim subject As String = "This is a testing email from Bob to John using SmtpClient"

			Dim emailMessage As New MailMessage With {
				.From = New MailAddress(from),
				.Body = "Testing email",
				.IsBodyHtml = True,
				.Subject = subject.Replace(vbCrLf, "")
			}

			emailMessage.To.Add([to])

			' 5. Attach images to email
			Dim altView As AlternateView = AlternateView.CreateAlternateViewFromString(htmlFile, Nothing, "text/html")

			For Each imgPath As String In imageList
				Using inputStream = File.OpenRead(imgPath)
					Using skBitmap = SKBitmap.Decode(inputStream)
						If skBitmap IsNot Nothing Then
							Dim ms = New MemoryStream()
							Using skImage = SKImage.FromBitmap(skBitmap)
							Using data = skImage.Encode(SKEncodedImageFormat.Png, 100)
								data.SaveTo(ms)
							End Using
							End Using

							ms.Position = 0

							Dim lr = New LinkedResource(ms) With {
								.ContentType = New ContentType("image/png"),
								.ContentId = Guid.NewGuid().ToString()
							}

							altView.LinkedResources.Add(lr)
						End If
					End Using
				End Using
			Next imgPath
			emailMessage.AlternateViews.Add(altView)

			' 6. Send the message using email account

			'client.UseDefaultCredentials = false;

			' Some smtp servers doesn't require credentials, therefore
			' you may set: client.UseDefaultCredentials = false;
			' and remove the line: client.Credentials = new NetworkCredential(userName, userPassword);

			' In the real example in case of the correct host, uncomment the line below:
			'client.Send(emailMessage);
			Console.WriteLine("The message has been sent!")
		End Sub
	End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:


Captcha

Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.