# Sending and Receiving Email

## Overview

The Mail Plugin in Servoy allows applications to send and receive emails programmatically. Emails can be sent using the SMTP protocol, while the plugin supports receiving emails via the older POP3 protocol. It supports various features including:

* Sending emails in plain text or HTML format.
* Adding attachments (binary or text).
* Handling multiple recipients via TO, CC, and BCC fields.
* Configuring SMTP properties dynamically.
* Receiving emails with attachments through POP3.

The [Mail Plugin Documentation](https://docs.servoy.com/reference/servoyextensions/server-plugins/mail#overview) provides comprehensive details about using the plugin for sending and receiving emails, including methods for attachments, error handling, and configuration.\
An external resource comparing [IMAP](https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol) and [POP](https://en.wikipedia.org/wiki/Post_Office_Protocol) protocols offers insights into their differences and use cases, useful for understanding which protocol to use for email retrieval.

## Email Configuration

### Configuring Mail Settings

Mail settings can be configured in the `servoy.properties` file or through the Admin Page under the Server Plugins section. Key points include:

* For SMTP relay setup, obtain host and authentication details from your email provider (e.g., Gmail).
* Defaults: If no SMTP relay is provided, the app server attempts to send mail on port 25, which may be blocked in corporate networks.

Example `servoy.properties` configuration:

```javascript
mail.smtp.host=smtp.sendgrid.net /*server*/
mail.smtp.auth=true
mail.smtp.user=username /*API Key Name*/
mail.smtp.password=password /*API Key Value*/
mail.smtp.port=587
```

**Servoy Admin Page**:

<div align="left"><figure><img src="https://3933488479-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjpWd52BKwABWxF2lScUK%2Fuploads%2Fgit-blob-97323246aa552d666c852c4db13492b2bd0972fb%2Fmail-server-plugin-servoy-admin2.jpg?alt=media" alt=""><figcaption></figcaption></figure></div>

This page is used to configure the settings for the Mail Server Plugin in Servoy. These settings define how the server connects to mail servers for sending and receiving emails, including support for SMTP, POP3, SSL/TLS, and other related options. Each field allows you to fine-tune the behavior of the mail service to match your server requirements, such as connection timeouts, authentication credentials, and security protocols.\
All the properties configured in the Servoy Admin Page, under the Server Plugin section's Mail Server Plugin subsection, will also appear in the servoy.properties file. This ensures consistency and allows manual adjustments if needed outside the admin interface.

The key configuration options include:

* SMTP Settings: For defining the outgoing mail server's host, port, authentication, and security details.
* POP3 Settings: For configuring the incoming mail server's host and APOP authentication support.
* Development Overrides: To specify developer-specific overrides like a default email address for testing purposes.

Each option includes an info link for additional details on its purpose and usage:

* `mail.server.allowUnauthenticatedRMIAccess`: Allow mailserver access for unauthenticated smart (rmi) client (true/false), defaults to false.
* `mail.pop3.host`: The name of POP3 server to recieve mails from.
* `mail.pop3.apop.enable`: Whether or not to use APOP for authentication (true/false), defaults to false.
* `mail.smtp.host`: The name of SMTP server to deliver the mails to.
* `mail.smtp.port`: The port of SMTP server to deliver the mails to.
* `mail.from`: Default 'from' address if none is specified.
* `mail.smtp.auth`: Use authentication (true/false), defaults to false.
* `mail.smtp.username`: Specify username if using authentication.
* `mail.smtp.password`: Specify password if using authentication.
* `mail.smtp.connectiontimeout`: Socket connection timeout value in milliseconds. Default is infinite timeout.
* `mail.smtp.timeout`: Socket I/O timeout value in milliseconds. Default is infinite timeout.
* `mail.smtp.ssl.enable`: Use SSL (true/false), defaults to false.
* `mail.smtp.starttls.enable`: Use START/TLS (true/false), defaults to false.
* `mail.mime.charset`: Specify the name of the charset to use for mail encoding (leave emtpy for system default), see <http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html> forinfo which charset names are usable.
* `mail.development.override.address`: Specify an email address to which all email will be send instead of the specified To, Cc and Bcc addresses. The specified to, Cc and Bcc addresses will be added to the Subject.

### Developer Override Address

For testing purposes, configure a developer override address:

```javascript
mail.override.to=developer@example.com
```

This ensures all emails are sent to a single address, regardless of the recipient specified in the code.

## Basic Examples

### Simple Email

Send a basic email:\
This example demonstrates sending a simple email with the essential fields: recipient, sender, subject, and message body.

```javascript
var success = plugins.mail.sendMail(
    'recipient@example.com', // Recipient email address
    'sender@example.com',   // Sender email address
    'Subject Line',         // Subject of the email
    'Email Body Text'       // Main body content of the email
);

if (!success) {
    application.output('Failed to send email: ' + plugins.mail.getLastSendMailExceptionMsg());
}
```

Explanation:\
Parameters:

* recipient: Specifies the recipient's email address.
* sender: Specifies the sender's email address.
* subject: Defines the subject of the email.
* body: Contains the main text or content of the email. If the email fails to send, the `getLastSendMailExceptionMsg` method retrieves details about the error.

### Multiple Recipients

Send email to multiple recipients with CC and BCC:\
This example shows how to send an email to multiple recipients using the TO, CC, and BCC fields.

```javascript
var success = plugins.mail.sendMail(
    'to@example.com,to2@example.com', // Comma-separated list of TO recipients
    'sender@example.com',            // Sender email address
    'Subject Line',                  // Subject of the email
    'Email Body',                    // Main body content of the email
    'cc@example.com',                // CC (carbon copy) recipients
    'bcc@example.com'                // BCC (blind carbon copy) recipients
);
  
if (!success) {
    application.output('Failed to send email: ' + plugins.mail.getLastSendMailExceptionMsg());
}
```

Explanation:\
Parameters:

* to: Specifies primary recipients of the email.
* sender: Specifies the sender's email address.
* subject: Defines the subject of the email.
* body: Contains the main text or content of the email.
* cc: Specifies recipients who receive a copy of the email and are visible to all recipients.
* bcc: Specifies recipients who receive a copy of the email but remain hidden from other recipients. Note: BCC recipients remain hidden from other recipients.

### Reply-To Address

Specify a different reply-to address:\
This example sends an email with a different Reply-To address.

```javascript
var success = plugins.mail.sendMail(
    'to@example.com',                       // Recipient email address
    'sender@example.com,replyto@example.com', // Sender email address and Reply-To address
    'Subject Line',                        // Subject of the email
    'Email Body'                           // Main body content of the email
);
```

Explanation:

* The sender parameter includes both the sender's email address and a Reply-To address, separated by a comma.
* The Reply-To address specifies where any email replies should be sent, instead of the sender's email address.

### Attachments

#### Binary attachment

This example creates a binary attachment using a local file. The [`createBinaryAttachment`](https://docs.servoy.com/guides/develop/programming-guide/sending-and-receiving-email) method reads the file and prepares it for inclusion in the email.

```javascript
var attachment = plugins.mail.createBinaryAttachment(
    'file.txt',                   // Name of the file as it appears in the email
    plugins.file.readFile('path/to/file.txt') // Reads the binary content of the file
);

var success = plugins.mail.sendMail(
    'to@example.com',
    'sender@example.com',
    'Subject Line',
    'Email Body',
    null,
    null,
    [attachment]
);
```

Explanation:\
Parameters:

* filename: The name displayed for the attachment in the email.
* binarydata: The file content read as binary data using the [`readFile`](https://docs.servoy.com/guides/develop/programming-guide/sending-and-receiving-email) method. This method prepares the attachment to be included in an email.

#### Text attachment

```javascript
var attachment = plugins.mail.createTextAttachment(
    'notes.txt',                  // Name of the text file to appear in the email
    'This is the content of the attachment' // Content of the text attachment
);

var success = plugins.mail.sendMail(
    'to@example.com',             // Recipient email address
    'sender@example.com',         // Sender email address
    'Subject with Text Attachment', // Subject of the email
    'Email body content',         // Main body content of the email
    null,                         // No CC recipients
    null,                         // No BCC recipients
    [attachment]                  // Attach the text file created above
);

if (!success) {
    application.output('Failed to send email: ' + plugins.mail.getLastSendMailExceptionMsg());
}
```

Explanation:

* The `createTextAttachment` method is used to create a text attachment with a specified file name and content.
* The `sendMail` method includes this attachment in the email sent to the recipient.
* Error handling ensures any issues during email sending are logged for troubleshooting.

## Overriding SMTP Properties

SMTP settings can be dynamically overridden, which is especially useful for multi-tenant applications.

Example:

```javascript
var properties = [
    'mail.smtp.host=smtp.tenantdomain.com', // SMTP host for tenant's email server
    'mail.smtp.user=user',                 // Username for SMTP authentication
    'mail.smtp.password=pass'             // Password for SMTP authentication
];

var success = plugins.mail.sendMail(
    'to@example.com',
    'sender@example.com',
    'Subject Line',
    'Email Body',
    null,
    null,
    null,
    properties
);
```

Explanation:\
Parameters:

* mail.smtp.host: Specifies the SMTP server address.
* mail.smtp.user: Sets the username for authenticating with the SMTP server.
* mail.smtp.password: Sets the password for authenticating with the SMTP server. This dynamic property configuration is helpful when each tenant has unique email server settings.

## Including Markup

HTML emails can include inline images and other markup.

Example:\
This example illustrates how to send an HTML email with embedded images using a content ID (cid).

```javascript
var htmlBody = '<html><body><h1>Hello</h1><p>This is an HTML email.</p><img src="cid:embedded"/></body></html>';
var imageAttachment = plugins.mail.createBinaryAttachment('embedded', plugins.file.readFile('path/to/image.jpg'));
var success = plugins.mail.sendMail(
    'to@example.com',
    'sender@example.com',
    'HTML Email',
    htmlBody,
    null,
    null,
    [imageAttachment]
);
```

Explanation:\
Parameters:

* htmlBody: Defines the HTML structure of the email content. The `cid` placeholder links the embedded image to display inline in the email. This example demonstrates creating an HTML email. The `cid` placeholder links the embedded image to the email body, making it display inline.

## Sending Bulk Mail

Use [`sendBulkMail`](https://docs.servoy.com/guides/develop/programming-guide/sending-and-receiving-email) to send emails in bulk, avoiding auto-replies like "Out of Office".

Example:\
In this example, each recipient in the array receives an individual email. Using a loop ensures that recipients don't see each other's addresses.

```javascript
var recipients = [
    'user1@example.com', // First recipient's email address
    'user2@example.com'  // Second recipient's email address
];

for (var i = 0; i < recipients.length; i++) {
    var success = plugins.mail.sendBulkMail(
        recipients[i],
        'sender@example.com',
        'Bulk Email',
        'Hello, this is a bulk email.'
    );
    if (!success) {
        application.output('Failed to send to ' + recipients[i]);
    }
}
```

Explanation:\
Parameters:

* recipients: An array containing email addresses of the recipients. Each address is processed in a loop to send emails individually, ensuring privacy. This loop demonstrates sending bulk emails to multiple recipients, sending each email individually.

## Handling Errors

Always check for errors after sending emails:

```javascript
var success = plugins.mail.sendMail('to@example.com', 'sender@example.com', 'Subject', 'Body');
if (!success) {
    var errorMessage = plugins.mail.getLastSendMailExceptionMsg();
    application.output('Error: ' + errorMessage);
}
```

## Receiving Mail

Use the [`receiveMail`](https://docs.servoy.com/guides/develop/programming-guide/sending-and-receiving-email) method to retrieve messages from a POP3 server.

Example:\
This example retrieves emails from a POP3 server, iterates through them, and logs their sender and subject.

```javascript
var messages = plugins.mail.receiveMail(
    'username',                                // Username for POP3 authentication
    'password',                                // Password for POP3 authentication
    true,                                      // Whether to leave messages on the server
    0,                                         // Receive mode: 0 (full messages)
    null,                                      // Only messages with a specific sent date (null = all messages)
    ['mail.pop3.host=pop3.example.com']        // POP3 host configuration
);

if (messages) {
    for (var i = 0; i < messages.length; i++) {
        var msg = messages[i];
        application.output('From: ' + msg.getFromAddresses());
        application.output('Subject: ' + msg.getSubject());
    }
} else {
    application.output('Failed to retrieve messages.');
}
```

Explanation: Parameters:

* username: POP3 account username.
* password: POP3 account password.
* leaveMsgsOnServer: If true, messages are not deleted from the server after retrieval.
* receiveMode: Determines the level of message content retrieved (0 for full messages).
* onlyReceiveMsgWithSentDate: Filters messages by their sent date (null for no filter).
* properties: Configures the POP3 server settings, including the host address. This example connects to a POP3 mail server to retrieve emails. The [`receiveMail`](https://docs.servoy.com/guides/develop/programming-guide/sending-and-receiving-email) method returns an array of messages, which are processed to extract details like the sender and subject.
