Send a Word file as an Email body
The example below shows how you can send a Word document as an email message using GemBox.Email and GemBox.Document components from a C# or VB.NET application by converting the DOC or DOCX file into an email body and adding additional content (such as subject, date, sender, and receiver). The generated email retains images, styles, and formatting from the Word template.
using GemBox.Document;
using GemBox.Email;
using GemBox.Email.Smtp;
using System;
using System.IO;
class Program
{
static void Main()
{
// If using the Professional version, put your GemBox.Email serial key below.
GemBox.Email.ComponentInfo.SetLicense("FREE-LIMITED-KEY");
// If using the Professional version, put your GemBox.Document serial key below.
GemBox.Document.ComponentInfo.SetLicense("FREE-LIMITED-KEY");
// Load a Word file.
var document = DocumentModel.Load("%#BodyTemplate.docx%");
using (var stream = new MemoryStream())
{
// Save as MHTML document.
document.Save(stream, new HtmlSaveOptions()
{
HtmlType = HtmlType.Mhtml,
UseContentIdHeaders = true
});
// Load MHTML content as a mail message.
var message = MailMessage.Load(stream, MailMessageFormat.Mhtml);
message.Subject = "Word message example";
message.Date = DateTime.Now;
message.From.Add(new MailAddress("sender@example.com"));
message.To.Add(new MailAddress("receiver@example.com"));
// Send the email.
using (var smtp = new SmtpClient("<HOST>"))
{
smtp.Connect();
smtp.Authenticate("<USERNAME>", "<PASSWORD>");
smtp.SendMessage(message);
}
}
}
}
Imports GemBox.Document
Imports GemBox.Email
Imports GemBox.Email.Smtp
Imports System
Imports System.IO
Module Program
Sub Main()
' If using the Professional version, put your GemBox.Email serial key below.
GemBox.Email.ComponentInfo.SetLicense("FREE-LIMITED-KEY")
' If using the Professional version, put your GemBox.Document serial key below.
GemBox.Document.ComponentInfo.SetLicense("FREE-LIMITED-KEY")
' Load a Word file.
Dim document = DocumentModel.Load("%#BodyTemplate.docx%")
Using stream As New MemoryStream()
' Save as MHTML document.
document.Save(stream, New HtmlSaveOptions() With
{
.HtmlType = HtmlType.Mhtml,
.UseContentIdHeaders = True
})
' Load MHTML content as a mail message.
Dim message = MailMessage.Load(stream, MailMessageFormat.Mhtml)
message.Subject = "Word message example"
message.Date = DateTime.Now
message.From.Add(New MailAddress("sender@example.com"))
message.To.Add(New MailAddress("receiver@example.com"))
' Send the email.
Using smtp As New SmtpClient("<HOST>")
smtp.Connect()
smtp.Authenticate("<USERNAME>", "<PASSWORD>")
smtp.SendMessage(message)
End Using
End Using
End Sub
End Module
The example code above demonstrates how to combine GemBox.Email and GemBox.Document, you can create emails from Word files by using the MHTML format as an intermediate. In other words, you can load a Word file into a DocumentModel
object and save it as HtmlType.Mhtml
, and then load it as a MailMessageFormat.Mhtml
email into MailMessage
.