Handling email with a custom App

2019-10-08 19:59:00.0
Developers

If you need to capture incoming emails, Either to create your own mail app, run scripts with the content of emails or trigger an event. You can do this in server side JavaScript in a custom app.

For more information on creating custom apps, see here.

Creating a mailbox controller is similar to any other controller on the custom app platform. The constructor to use is mailboxController().

Here is an example:

controllerMappings
        .mailboxController()
        .enabled(true)
        .verifyMailbox('verifyMailbox')
        .storeMail('storeMail')
        .build();

This will create a MailboxMapping.

When an email is received by the server, It calls two methods, the first one is verifyMailbox, the second one is storeMail.

Verify Mailbox

The verifyMailbox method gets called when the email is first being sent to the server, this method is used to see if the incoming email should be captured by this mailbox or not.

Two arguments gets passed to this method:

  1. WebsiteRootFolder
  2. MailboxAddress

This method should return a boolean, true if this mailbox is to be used and false if not. Here is an example:

function verifyMailbox(page, to) {
    if ("bloggs.com" === to.domain) {
        return true;
    }
    return false;
}

 

Store Mail

The storeMail method get's called after the verifyMethod returns true. This method handles the incoming email.

Three arguments gets passed to this method:

  1. WebsiteRootFolder
  2. MailboxAddress
  3. RepoMailboxStandardMessage

Now the method can process the email and any attachments as it needs, Here is an example:

function storeMail(page, to, msg) {
    log.info('Received an email from: {}', to);
    log.info('From: {} - Subject: {}', msg.from, msg.subject);
    log.info('Text: {}', msg.text);
    log.info('HTML: {}', msg.html);

    for each(var att in msg.attachments) {
        log.info('File Name: {} - Content Type: {}', att.name, att.contentType);
    }
}

 

MailboxAddress

This object holds the email address information. It has the following properties:

  • displayName - Returns a representative name for this address. This is the personal portion if present, otherwise it is the user portion.
  • user - Returns the user portion of the email address
  • personal - Returns the personal name of the email address if present.
  • domain - Returns the domain name portion of the email address

And the following methods:

  • toString() - Returns a string representation of the email address. e.g. "Joe Bloggs"
  • toPlainAddress() - Returns a string representation of the email address excluding the personal portion. joe@bloggs.com