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


Полный код

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();
        }
    }
}

Скачать

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

Скачать

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


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.