Skip to main content

Email Reports

  • 9 minutes to read

This document contains examples of how to email a report in code, from the Web Document Viewer and Blazor Report Viewer.

Email a Report in Code

Send a Report as PDF Attachment

You can export a report to PDF and attach the PDF document to the email message.

For each report class you can specify different email export options in the Visual Studio Designer:

Report Email Options

View Example: Reporting for WinForms - Use MailKit to Email a Report

The following code exports a report to PDF, attaches the PDF document to a message, and sends the message using email options specified in the Visual Studio Report Designer. This code uses the MailKit library.

using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using System;
using System.IO;
using System.Threading.Tasks;
// ...
private static MimeMessage CreateMimeMessageExportToPdf(MemoryStream stream)
{
    // Instantiate a report. 
    // Email export options are already specified at design time.                
    XtraReport1 report = new XtraReport1();

    var message = new MimeMessage();
    message.From.Add(new MailboxAddress("Someone", "someone@test.com"));
    message.To.Add(new MailboxAddress(report.ExportOptions.Email.RecipientName,
        report.ExportOptions.Email.RecipientAddress));
    message.Subject = report.ExportOptions.Email.Subject;
    var builder = new BodyBuilder();
    builder.TextBody = "This is a test e-mail message sent by an application.";
    // Create a new attachment and add the PDF document.
    report.ExportToPdf(stream);
    stream.Seek(0, System.IO.SeekOrigin.Begin);
    builder.Attachments.Add("TestReport.pdf", stream.ToArray(), new ContentType("application","pdf"));
    message.Body = builder.ToMessageBody();
    return message;
}
// ...
private async void btnSend_Click(object sender, EventArgs e)
{
    string SmtpHost = edtHost.EditValue.ToString();
    int SmtpPort = Int32.Parse(edtPort.EditValue.ToString());
    string SmtpUserName = edtUsername.EditValue.ToString();
    string SmtpUserPassword = edtPassword.EditValue.ToString();
    lblProgress.Text = "Sending mail...";
    lblProgress.Text = await SendAsync(SmtpHost, SmtpPort, SmtpUserName, SmtpUserPassword);
}

private async Task<string> SendAsync(string smtpHost, int smtpPort, string userName, string password)
{
    string result = "OK";
    // Create a new memory stream and export the report in PDF.
    using (MemoryStream stream = new MemoryStream())
    {
        using (MimeMessage mail = CreateMimeMessage(stream))
        {
            using (var client = new SmtpClient())
            {
                try {
                    client.Connect(smtpHost, smtpPort, SecureSocketOptions.Auto);
                    //client.Authenticate(userName, password);
                    await client.SendAsync(mail);
                }
                catch (Exception ex) {
                    result = ex.Message;
                }
                client.Disconnect(true);
            }
        }
    }
    return result;
}

Send a Report as HTML Email Body

Export a report as an email and use the MailKit library to send it.

To export a report to an email message, do the following:

View Example: Reporting for WinForms - How to Use MailKit to Email a Report

using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using System;
using System.IO;
using System.Threading.Tasks;
// ...
private static MimeMessage CreateMimeMessageExportToMail(MemoryStream stream) {
    // Instantiate a report. 
    // Email export options are already specified at design time.                
    XtraReport1 report = new XtraReport1();

    System.Net.Mail.MailMessage mMessage = report.ExportToMail("someone@test.com",
                report.ExportOptions.Email.RecipientAddress, report.ExportOptions.Email.RecipientName);
    mMessage.Subject = report.ExportOptions.Email.Subject;

    // Create a new attachment and add the PDF document.
    report.ExportToPdf(stream);
    stream.Seek(0, System.IO.SeekOrigin.Begin);
    System.Net.Mail.Attachment attachedDoc = new System.Net.Mail.Attachment(stream, "TestReport.pdf", "application/pdf");
    mMessage.Attachments.Add(attachedDoc);

    var message = (MimeMessage)mMessage;
    return message;
}

private async void btnSend_Click(object sender, EventArgs e)
{
    string SmtpHost = edtHost.EditValue.ToString();
    int SmtpPort = Int32.Parse(edtPort.EditValue.ToString());
    string SmtpUserName = edtUsername.EditValue.ToString();
    string SmtpUserPassword = edtPassword.EditValue.ToString();
    lblProgress.Text = "Sending mail...";
    lblProgress.Text = await SendAsync(SmtpHost, SmtpPort, SmtpUserName, SmtpUserPassword);
}

private async Task<string> SendAsync(string smtpHost, int smtpPort, string userName, string password)
{
    string result = "OK";
    // Create a new memory stream and export the report in PDF.
    using (MemoryStream stream = new MemoryStream())
    {
        using (MimeMessage mail = CreateMimeMessage(stream))
        {
            using (var client = new SmtpClient())
            {
                try {
                    client.Connect(smtpHost, smtpPort, SecureSocketOptions.Auto);
                    //client.Authenticate(userName, password);
                    await client.SendAsync(mail);
                }
                catch (Exception ex) {
                    result = ex.Message;
                }
                client.Disconnect(true);
            }
        }
    }
    return result;
}

Email a Report from the Web Document Viewer

You can send a request to the server to export a report to PDF and email the resulting PDF document.

View Example: Reporting for Web - Email a Report from the Document Viewer

Do the following on the client and server sides:

Configure Server Side

  1. Create a DocumentOperationService class descendant and override CanPerformOperation) and PerformOperation methods.

  2. Implement the PerformOperation method that exports a report to PDF, composes the mail message, and uses the SmtpClient instance to send a message:

    public override DocumentOperationResponse PerformOperation(DocumentOperationRequest request, 
        PrintingSystemBase initialPrintingSystem, 
        PrintingSystemBase printingSystemWithEditingFields) {
        using (var stream = new MemoryStream()) {
            System.Net.Mail.MailMessage mMessage = 
                printingSystemWithEditingFields.ExportToMail(request.CustomData,
                "john.doe@test.com",
                "John Doe");
            mMessage.Subject = "Test";
    
            // Create a new attachment and add the PDF document.
            printingSystemWithEditingFields.ExportToPdf(stream);
            stream.Seek(0, System.IO.SeekOrigin.Begin);
            System.Net.Mail.Attachment attachedDoc = 
                new System.Net.Mail.Attachment(stream, "TestReport.pdf", "application/pdf");
            mMessage.Attachments.Add(attachedDoc);
    
            var message = (MimeKit.MimeMessage)mMessage;
    
            string smtpHost = "localhost";
            int smtpPort = 25;
    
    
            using (message) {
                using (var client = new MailKit.Net.Smtp.SmtpClient()) {
                    try {
                        client.Connect(smtpHost, smtpPort, SecureSocketOptions.Auto);
                        //client.Authenticate(userName, password);
                        client.Send(message);
                        client.Disconnect(true);
                        return new DocumentOperationResponse {
                            Succeeded = true,
                            Message = "Mail was sent successfully",
                            DocumentId = printingSystemWithEditingFields.Document.Name
                        };
                    }
                    catch (Exception ex) {
                        return new DocumentOperationResponse {
                            Message = ex.Message, 
                            Succeeded = false,
                        };
                    }
                }
            }
        }
    }
    
  3. Register an instance of a custom DocumentOperationService class as a service:

    DefaultWebDocumentViewerContainer.Register<DocumentOperationService, Services.CustomDocumentOperationService>();
    

Configure Client Side

  1. Call the PerformCustomDocumentOperation method to pass an email address to the DocumentOperationService on the server.

    The code snippet below handles the CustomizeMenuActions event to add a Send via Email button to the toolbar and calls the PerformCustomDocumentOperation method on button click:

    function CustomizeMenuActions(s, e) {
        var itemDisabled = ko.observable(true);
        s.Init.AddHandler(function (s) {
            var reportPreview = s.GetReportPreview();
            reportPreview.events.on('propertyChanged', (e) => {
                if(e.propertyName === 'exportDisabled') {
                    itemDisabled(e.newValue);
                }
            });
            itemDisabled(reportPreview.exportDisabled);
        });
        var sendViaEmailItem = {
            id: 'someCustomId',
            imageClassName: 'custom-image-item',
            text: 'Send via Email',
            visible: true,
            disabled: itemDisabled,
            clickAction: function () {
                s.PerformCustomDocumentOperation('someone@test.com')
                    .done((arg) => alert('Document ' + arg.documentId + " : " + arg.message));
            }
        };
        e.Actions.push(sendViaEmailItem);
    }
    

Email a Report from the Native Blazor Report Viewer

Use the Mailkit library to send an email from the native Blazor Report Viewer. You can find a complete code sample here: Email a Report from the Native Blazor Report Viewer.

The example adds a Send Email button to the Viewer’s toolbar. The button opens the Send Email dialog (DxPopup). You can specify the recipient list, subject, attachment, and body within the dialog. Click the Send button to send the report with the specified settings.

View Example: Reporting for Blazor - Email a Report from the Native Blazor Report Viewer