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


Complete code

using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Drawing;
using System.Collections.Generic;

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
            string rtfString = File.ReadAllText(rtfFile);
            SautinSoft.RtfToHtml r = new SautinSoft.RtfToHtml();
            r.ImageStyle.IncludeImageInHtml = false;
            List<SautinSoft.RtfToHtml.SautinImage> imageList = new List<SautinSoft.RtfToHtml.SautinImage>();

            // 2. After launching this method we'll get our RTF document in HTML format
            // and list of all images.
            r.OpenRtf(rtfString);
            string htmlString = String.Empty;
			r.ToHtml(out htmlString, imageList);

            // 3. 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();
            emailMessage.From = new MailAddress(from);
            emailMessage.To.Add(to);
            emailMessage.Subject = subject.Replace("\r\n", "");

            // 4. Attach images to email
            System.Net.Mail.AlternateView altView = AlternateView.CreateAlternateViewFromString(htmlString, null, "text/html");

            foreach (SautinSoft.RtfToHtml.SautinImage simg in imageList)
            {
                if (simg.Img != null)
                {
                    LinkedResource lr = null;
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    simg.Img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    if (ms != null && ms.Position > 0)
                        ms.Position = 0;
                    lr = new LinkedResource(ms);
                    lr.ContentId = simg.Cid;
                    altView.LinkedResources.Add(lr);
                }
            }
            emailMessage.AlternateViews.Add(altView);

            // 5. Send the message using email account
            string userName = "bobuser";
            string userPassword = "bobpassword";

            SmtpClient client = new SmtpClient();
            client.Port = 25;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

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

            client.Credentials = new NetworkCredential(userName, userPassword);
            client.Host = "smtpout.bobsite.com";
            
            // In the real example in case of the correct host, uncomment the line below:
            //client.Send(emailMessage);
            Console.WriteLine("The message has been sent!");
            Console.ReadKey();
        }
    }
}

Download

Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports System.Drawing
Imports System.Collections.Generic

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 rtfString As String = File.ReadAllText(rtfFile)
            Dim r As New SautinSoft.RtfToHtml()
            r.ImageStyle.IncludeImageInHtml = False
            Dim imageList As New List(Of SautinSoft.RtfToHtml.SautinImage)()

            ' 2. After launching this method we'll get our RTF document in HTML format
            ' and list of all images.
            r.OpenRtf(rtfString)
            Dim htmlString As String = String.Empty
            r.ToHtml(htmlString, imageList)

            ' 3. 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()
            emailMessage.From = New MailAddress(from)
            emailMessage.To.Add([to])
            emailMessage.Subject = subject.Replace(vbCrLf, "")

            ' 4. Attach images to email
            Dim altView As System.Net.Mail.AlternateView = AlternateView.CreateAlternateViewFromString(htmlString, Nothing, "text/html")

            For Each simg As SautinSoft.RtfToHtml.SautinImage In imageList
                If simg.Img IsNot Nothing Then
                    Dim lr As LinkedResource = Nothing
                    Dim ms As New System.IO.MemoryStream()
                    simg.Img.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
                    If ms IsNot Nothing AndAlso ms.Position > 0 Then
                        ms.Position = 0
                    End If
                    lr = New LinkedResource(ms)
                    lr.ContentId = simg.Cid
                    altView.LinkedResources.Add(lr)
                End If
            Next simg
            emailMessage.AlternateViews.Add(altView)

            ' 5. Send the message using email account
            Dim userName As String = "bobuser"
            Dim userPassword As String = "bobpassword"

            Dim client As New SmtpClient()
            client.Port = 25
            client.DeliveryMethod = SmtpDeliveryMethod.Network

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

            client.Credentials = New NetworkCredential(userName, userPassword)
            client.Host = "smtpout.bobsite.com"

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

Download

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


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:



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.