XtremeDocumentStudio .NET
Next-generation multi-format document-processing component suite for .NET developers
Compatibility
Visual Studio 2010/2012/2013/2015

How to e-mail mail-merged DOCX, DOC, PDF and images using XtremeDocumentStudio .NET

Learn to use the new "EMailAction" action class.

When the mail-merge functionality was introduced in XtremeDocumentStudio, it could create the document and save them to files or streams. In February, we added the ability to e-mail the document to a set of recipients. For this, a new class EMailAction has been introduced. In this article, you can see how to use it.

The Merge() method accepts a PostMergeAction instance. This could be an instance of one of the three derived classes.

public MailMergeResult Merge(
    PostMergeAction postMergeAction
);

To e-mail mail-merged documents, you need to call the Merge() method with a new instance of the EMailAction instance. For this, you will need to set the Message, UseMergedDocumentAs and SMTPServerSettings properties. You use the Message property to set the from, to, subject and body parts of the e-mail. You use the SMTPServerSettings to set the outgoing mail server settings. UseMergedDocumentAs accepts an enum value that lets you compose the merged document content as the body of the e-mail or as a simple attachment.

A mail-merge example

For this article, I used the same code snippet from the previous article and made some changes. A Gmail account was used to send email. The CUSTOMERS table did not have an e-mail column and so I added an "Email" column. It was populated with bogus e-mail addresses made up from the ID column. I had also updated the SQL statement in the data source configuration so that I would only hit a few mysterious customers in Italy.

public partial class Form1 : Form {

  public Form1() {
    InitializeComponent();
    Gnostice.Documents.Framework.ActivateLicense(XDOC_LICENSE_KEY);
  }

  private void button1_Click(object sender, EventArgs e) {
    try {
      /*
       * Set up data source
       */ 
      DataSet ds = new DataSet();
      OleDbConnection conn =
          new OleDbConnection(
                  "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=FPNWIND.MDB");
      conn.Open();
      OleDbDataAdapter da =
          new OleDbDataAdapter(
              "SELECT ContactName, Address, City, PostalCode, Country, Email " +
              " FROM Customers " +
              " WHERE Country='Italy' " +
              " ORDER BY ContactName",
              conn);
      da.Fill(ds);
      DataTable dt = ds.Tables[0];


      /*
       * Set up a mail action for the mail-merge operation
       */ 
      EMailAction oMailAction = new EMailAction();
      oMailAction.SMTPServerSettings =
          new SMTPServerSettings("smtp.gmail.com", 587) {
            EnableSsl = true,
            UseDefaultCredentals = false,
            CustomNetworkCredential =
            new System.Net.NetworkCredential(
                "REPLACE-WITH-USERNAME@gmail.com",
                "REPLACE-PASSWORD")
          };
      oMailAction.UseMergedDocumentAs = MergedDocumentOptions.Attachment;
      oMailAction.Message = new Gnostice.Documents.Message();
      oMailAction.Message.From = "REPLACE-WITH-USERNAME@gmail.com";
      oMailAction.Message.To.Clear();
      // Set recipient name and email address in the To field using placeholders
      oMailAction.Message.To.Add("{{ContactName}} <{{Email}}>");
      oMailAction.Message.Subject = "Payment reminder";
      oMailAction.Message.Body =
        "Hi {{ContactName}},\n\nPFA important reminder regarding your loan."+
        "\n\nV. Subhash\nBank of Internet";
      oMailAction.BeforeSend += oMailAction_BeforeSend;
      oMailAction.AfterSend += oMailAction_AfterSend;

      /*
       * Do mail-merge
       */
      // Initialize mail-merge
      MailMerge mm = new MailMerge();

      // Specify mail-merge template document
      mm.TemplateFileName = "letter_envelope_template.docx";

      // Specify mail-merge input data
      mm.DataSource = dt;
      Console.WriteLine("Found " + dt.Rows.Count + " records");

      // Remove unfilled fields
      mm.MailMergeCleanupOptions = MailMergeCleanupOptions.RemoveUnmappedFields;

      // Set handler for EndJob event to show the final result
      mm.EndJob += mm_EndJob;

      // Mail-merge 
      mm.Merge(oMailAction);

      // Clean up
      conn.Close();
    } catch (Exception err) {
      MessageBox.Show(err.Message.ToString());
    }

  }
  
  void oMailAction_BeforeSend(object sender, MailMergeSendBeginEventArgs e) {
    Console.Write("Mail to be sent to " + e.Message.To[0]);
  }

  void oMailAction_AfterSend(object sender, MailMergeSendCompleteEventArgs e) {
    Console.WriteLine("... Done.");
  }

}

Sure enough, the mail got sent.

Gmail or Google Docs seems to have an issue with documents that has pages with different sizes. When you download it and open it in Miss Word, you can see that the documents have been merged all right.

The mail-merge operation is a blocking action. If you have a long list, you will have to call it asynchronously to prevent Windows from assuming that your software has become unresponsive. Of course, you don't have do it asynchronously in a service.

---o0O0o---

Our .NET Developer Tools
XtremeDocumentStudio .NET

Multi-format document-processing component suite for .NET developers.

PDFOne .NET

A .NET PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, and bookmark PDF documents in .NET applications.

Our Delphi/C++Builder developer tools
XtremeDocumentStudio Delphi

Multi-format document-processing component suite for Delphi/C++Builder developers, covering both VCL and FireMonkey platforms.

eDocEngine VCL

A Delphi/C++Builder component suite for creating documents in over 20 formats and also export reports from popular Delphi reporting tools.

PDFtoolkit VCL

A Delphi/C++Builder component suite to edit, enhance, view, print, merge, split, encrypt, annotate, and bookmark PDF documents.

Our Java developer tools
XtremeDocumentStudio (for Java)

Multi-format document-processing component suite for Java developers.

PDFOne (for Java)

A Java PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, bookmark PDF documents in Java applications.

Our Platform-Agnostic Cloud and On-Premises APIs
StarDocs

Cloud-hosted and On-Premises REST-based document-processing and document-viewing APIs

Privacy | Legal | Feedback | Newsletter | Blog | Resellers © 2002-2017 Gnostice Information Technologies Private Limited. All rights reserved.