ballerina/email

Overview

This module provides APIs to perform email operations such as sending and reading emails using the SMTP, POP3, and IMAP4 protocols.

Client

This module supports the following three client types.

  • email:SmtpClient - The client, which supports sending an email using the SMTP protocol.
  • email:PopClient - The client, which supports receiving an email using the POP3 protocol.
  • email:ImapClient - The client, which supports receiving an email using the IMAP4 protocol.

SMTP Client

To send an email using the SMTP protocol, you must first create an email:SmtpClient object. The code for creating an email:SmtpClient can be found below.

Creating a client

The following code creates an SMTP client, which connects to the default port(465) and enables SSL.

1email:SmtpClient smtpClient = check new ("smtp.email.com", "sender@email.com", "pass123");

The port number of the server can be configured by passing the following configurations.

1email:SmtpConfiguration smtpConfig = {
2 port: 465
3};
4
5email:SmtpClient smtpClient = check new ("smtp.email.com", "sender@email.com", "pass123", smtpConfig);
Sending an email

Once the email:SmtpClient is created, an email can be sent using the SMTP protocol through that client. Samples for this operation can be found below.

1email:Message email = {
2 to: ["receiver1@email.com", "receiver2@email.com"],
3 cc: ["receiver3@email.com", "receiver4@email.com"],
4 bcc: ["receiver5@email.com"],
5 subject: "Sample Email",
6 body: "This is a sample email.",
7 'from: "author@email.com",
8 sender: "sender@email.com",
9 replyTo: ["replyTo1@email.com", "replyTo2@email.com"]
10};
11
12check smtpClient->sendMessage(email);

An email can be sent directly by calling the client specifying optional parameters as named parameters as well. Samples for this operation can be found below.

1email:Error? response = smtpClient->send(
2 ["receiver1@email.com", "receiver2@email.com"],
3 "Sample Email",
4 "author@email.com",
5 body="This is a sample email.",
6 cc=["receiver3@email.com", "receiver4@email.com"],
7 bcc=["receiver5@email.com"],
8 sender="sender@email.com",
9 replyTo=["replyTo1@email.com", "replyTo2@email.com"]
10);

POP3 Client

To receive an email using the POP3 protocol, you must first create an email:PopClient object. The code for creating an email:PopClient can be found below.

Creating a client

The following code creates a POP3 client, which connects to the default port(995) and enables SSL.

1email:PopClient popClient = check new ("pop.email.com", "reader@email.com", "pass456");

The port number of the server can be configured by passing the following configurations.

1email:PopConfiguration popConfig = {
2 port: 995
3};
4
5email:PopClient popClient = check new ("pop.email.com", "reader@email.com", "pass456", popConfig);
Receiving an email

Once the email:PopClient is created, emails can be received using the POP3 protocol through that client. Samples for this operation can be found below.

1email:Message? emailResponse = check popClient->receiveMessage();

IMAP4 Client

To receive an email using the IMAP4 protocol, you must first create an email:ImapClient object. The code for creating an email:ImapClient can be found below.

Creating a client

The following code creates an IMAP4 client, which connects to the default port(993) and enables SSL.

1email:ImapClient imapClient = check new ("imap.email.com", "reader@email.com", "pass456");

The port number of the server and/or the SSL support can also be configured by passing the following configurations.

1email:ImapConfiguration imapConfig = {
2 port: 993,
3 enableSsl: true
4};
5
6email:ImapClient imapClient = check new ("imap.email.com", "reader@email.com", "pass456", imapConfig);
Receiving an email

Once the email:ImapClient is created, emails can be received using the IMAP4 protocol through that client. Samples for this operation can be found below.

1email:Message? emailResponse = check imapClient->receiveMessage();

POP3 and IMAP Listeners

As POP3 and IMAP4 protocols are similar in the listener use cases, POP3 is considered in the examples below. In order to receive emails one-by-one from a POP3 server, you must first create an email:PopListener object. The code for creating an email:PopListener can be found below.

1listener email:PopListener emailListener = check new ({
2 host: "pop.email.com",
3 username: "reader@email.com",
4 password: "pass456",
5 pollingInterval: 2,
6 port: 995
7});

Once initialized, a service can listen to the new emails as follows. New emails get received at the onMessage method and when errors happen, the onError method gets called.

1service "emailObserver" on emailListener {
2
3 remote function onMessage(email:Message emailMessage) {
4 io:println("Email Subject: ", emailMessage.subject);
5 io:println("Email Body: ", emailMessage.body);
6 }
7
8 remote function onError(email:Error emailError) {
9 io:println("Error while polling for the emails: " + emailError.message());
10 }
11
12}

Security and Authentication

The email module supports both the TLS/SSL and STARTTLS as transport-level security protocols.

Transport-level security for all SMTP, POP3, and IMAP clients/listeners can be configured with the secureSocket field.

1secureSocket: {
2 cert: "path/to/certfile.crt",
3 protocol: {
4 name: TLS,
5 versions: ["TLSv1.2", "TLSv1.1"]
6 },
7 ciphers: ["TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"],
8 verifyHostName: true
9}

Transport-level security for the SMTP client configuration can be defined as follows.

1email:SmtpConfiguration smtpConfig = {
2 port: 465,
3 secureSocket: {
4 // Transport level configuration
5 }
6};

Transport-level security for the POP3 client configuration can be defined as follows.

1email:PopConfiguration popConfig = {
2 port: 995,
3 secureSocket: {
4 // Transport level configuration
5 }
6};

Transport-level security for the IMAP client configuration can be defined as follows.

1email:ImapConfiguration imapConfig = {
2 port: 993,
3 secureSocket: {
4 // Transport level configuration
5 }
6};

Transport-level security for the POP3 listener configuration can be defined as follows.

1email:PopListenerConfiguration popListenerConfig = {
2 host: "127.0.0.1",
3 username: "hascode",
4 password: "abcdef123",
5 pollingInterval: 2,
6 port: 995,
7 secureSocket: {
8 // Transport level configuration
9 }
10};

Transport-level security for the IMAP listener configuration can be defined as follows.

1email:ImapListenerConfiguration imapListenerConfig = {
2 host: "127.0.0.1",
3 username: "hascode",
4 password: "abcdef123",
5 pollingInterval: 2,
6 port: 993,
7 secureSocket: {
8 // Transport level configuration
9 }
10};

By default, TLS/SSL is enabled as the default transport-level security protocol, and the certificate verification is set as required. This optional protocol definition can be configured with the security enum field in each of the configuration types described above.

The options available with the security field are as follows.

  1. SSL - As same as the default TLS/SSL protocol
  2. START_TLS_NEVER - Disables both TLS/SSL and STARTTLS protocols and allows only the unencrypted transport-level communication
  3. START_TLS_ALWAYS - Makes it mandatory to use the secure STARTTLS protocol
  4. START_TLS_AUTO - Enables the STARTTLS protocol, which would switch to the unsecured communication mode if the secure STARTTLS mode is not available in the server

The following is an example of using the security field in the SMTP client with the START_TLS_AUTO mode.

1email:SmtpConfiguration smtpConfig = {
2 port: 587,
3 secureSocket: {
4 // Transport level configuration
5 },
6 security: START_TLS_AUTO
7};

Similarly, other client/listener configuration types can also be defined with the security field.

Note: Make sure the port number is changed accordingly depending on the protocol used.

Standard port numbers used for each of the protocol for each type of transport security are as given below.

Protocol/SecuritySSLSTARTTLSUnsecure
SMTP46558725, 587
POP3995995110
IMAP4993143, 993143

All the authentications are based on the username/password credentials.

Note: When the 'from field is not provided in an email:Message, the username field of the initialization argument of the email:SmtpClient is set as the from address of an email to be sent with SMTP.

Message Content and Attachments

An email:Message prepared to be sent can have the text body content, body, and/or HTML body content (htmlBody). When emails are received with POP3 or IMAP, the text email bodies and HTML bodies of the email are captured by the body and htmlBody fields of the email:Message respectively.

When sending emails with SMTP, there are four options to specify the email attachments in the email:Message.

  1. With the email:Attachment type, which points to an attachment file along with its content-type
  2. With an array of the email:Attachment type
  3. With the mime:Entity type
  4. With an array of the mime:Entity type

Option 1 and 2 are designed for ordinary users to attach files from the local machine along with its content-type. Option 3 and 4 are designed for advanced users who have programming knowledge to define complex MIME typed data attachments.

The following is an example of attaching a PDF file to an email with option 1.

1email:Attachment pdfAttachment = {filePath: "path/to/application.pdf", contentType: "application/pdf"};
2
3email:Message email = {
4 // Other fields
5 attachments: pdfAttachment
6};

The following is an example of attaching a JPG file to an email with option 3.

1mime:Entity imageAttachment = new;
2mime:ContentDisposition disposition = new;
3disposition.fileName = "profilePic.jpg";
4disposition.disposition = "attachment";
5disposition.name = "profilePic";
6imageAttachment.setContentDisposition(disposition);
7imageAttachment.setContentId("ImageAttachment");
8imageAttachment.setFileAsEntityBody("path/to/profilePic.jpg", mime:IMAGE_JPEG);
9
10email:Message email = {
11 // Other fields
12 attachments: imageAttachment
13};

Clients

[3]

ImapClient

Represents an IMAP Client, which interacts with an IMAP Server.

PopClient

Represents a POP Client, which interacts with a POP Server.

SmtpClient

Represents an SMTP Client, which interacts with an SMTP Server.

Classes

[2]

ImapListener

Represents a service listener that monitors the email server location.

PopListener

Represents a service listener that monitors the email server location.

Records

[9]

Attachment

Email attachment.

ImapConfiguration

Configuration of the IMAP Endpoint.

ImapListenerConfiguration

Configuration for Email listener endpoint.

Message

Email message properties.

Options

Optional parameters for an Email message.

PopConfiguration

Configuration of the POP Endpoint.

PopListenerConfiguration

Configuration for Email listener endpoint.

SecureSocket

Secure Socket configuration.

SmtpConfiguration

Configuration of the SMTP Endpoint.

Constants

[1]

DEFAULT_FOLDER

Default folder to read emails.

Enums

[2]

Protocol

Represents protocol options.

Security

Security type.

Errors

[1]

Error

Defines the common error type for the module