Send a HTML mail from an XPage with only 5 lines of code

Sending an e-mail from an XPage (using SSJS) is not too difficult, especially if you’ve done it before in LotusScript:

var doc:NotesDocument = database.createDocument();

doc.replaceItemValue("form", "Memo");
doc.replaceItemValue("sendTo", "");
doc.replaceItemValue("subject", "hi there!");
doc.replaceItemValue("body", "content here");

It gets a bit more difficult though if you want to send out HTML mails. To create those you need to work with stuff like MIME entities, MIME headers and streams.

I’ve created a SSJS library that makes it easy to create HTML mails. It allows you to do the following:

  • create HTML mails in a really simple way
  • add one or more attachments, either from document or files on the server
  • change the sender (name and email address)

To use the library you first need to add it to your application: create a new SSJS script library, call it xpHTMLMail and copy this code from the XSnippets site to it.

Next, in the code where you want to use it you can import that library by adding the following:

import xpHTMLMail;

To create a basic HTML message you write:

var mail = new HTMLMail();

mail.setTo( "" );
mail.setSubject( "Hi there!" );
mail.addHTML( "&lt;b&gt;Hi there!&lt;b&gt;" );<br clear="none" />mail.send();

You can add more HTML to the body of the email by making subsequent calls to the addHTML() function. The library also has methods to set the CC or BCC users:

mail.setCC( ["", ""] );
mail.setBB( "" );

The setTo(), setCC() and setBCC() methods accept a string or array of strings.

What about attachments?

The class has two methods to add attachments to a message: you can add them either from a document in the current application or from a file on the server.

1. To add a file from a document you need to specify the document’s unid and file name:

mail.addDocAttachment("5203C670815BC8C4C12579270029C543", "jellyfish.jpg");

Note that files from documents are read directly from the document into a stream and added as a MIME entity to the message. The files aren’t extracted first.

2. To add a file that’s store somewhere on the server’s filesystem you need to specify its path and file name:

mail.addFileAttachment( "c:/temp/", "report.pdf");
Changing the sender

The sender of the message can be changed by using the setSender() method. You have to specify an e-mail address and can optionally specify a name:



setSender("", "Some User");