Export to MailMessage

  • 3 minutes to read

You can export a report as an email and use the .NET Framework SMTP client to send it.

To do this, call the XtraReport.ExportToMail method. This method returns an instance of the MailMessage class. The body of the resulting message contains a document in HTML format, optimized for email. Use the SmtpClient to send the email.

If you want to customize the email's content and format, create an instance of the MailMessageExportOptions class and pass it as an argument to the XtraReport.ExportToMail(MailMessageExportOptions) method.

The following code creates an email with the report included in the message body in HTML format, and sends the email. Note that you should specify the SMTP hostname and port number. If your SMTP server requires authentication, specify the username and password.

View Example: How to Send a Report as HTML in an Email Body

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using DevExpress.XtraReports.UI;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            List<ReportData> list = new List<ReportData>();
            for(int i = 0; i < 10; i++)
                list.Add(new ReportData() { Value1 = i, Value2 = i, Value3 = i });

            XtraReport report = new XtraReport1() { DataSource = list };

            string SmtpHost = null;
            int SmtpPort = -1;
            if (string.IsNullOrEmpty(SmtpHost) || SmtpPort == -1)
            {
                System.Diagnostics.Debug.WriteLine("Please configure the SMTP server settings.");
                return;
            }

            string SmtpUserName = "Enter_Sender_User_Name";
            string SmtpUserPassword = "Enter_Sender_Password";

            using (var smtpClient = new SmtpClient(SmtpHost, SmtpPort))
            {
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.EnableSsl = false;

                if (!string.IsNullOrEmpty(SmtpUserName))
                {
                    smtpClient.Credentials = new NetworkCredential(SmtpUserName, SmtpUserPassword);
                }
                using(MailMessage message = report.ExportToMail("someone@example.com",
                        "recipient1@example.com, recipient2@example.com, recipient3@example.com", "Enter_Message_Subject")) {
                    smtpClient.Send(message);
                }
            }   
        }
    }
}
NOTE

Document navigation in a report is based on scripts. To use navigation based on HTML links, enable the UseHRefHyperlinks setting in the MailMessageExportOptions instance and pass this instance to the ExportToMail method as an argument.