# Email Service

## Introduction

Our email service is a connector to SMTP-based email server and SendGrid email service. It supports sending out emails with a plain text body or attachment in a business scenario like policy issuance. The manual and restful APIs are provided for user.

## Usage Scenarios

Email service is designed to help digital marketers and application developers send marketing, notifications, and business emails. It is a reliable, economical, and practical service for enterprises of all sizes that contact customers with email. The user can configure their own email account before using the service. 

## Apply for an email sender

```mermaid
flowchart 
  s1@{ shape: hex, label: "I have my own _aws ses credentials_ / _smtp server_ / _sendgrid account_."}
  s2.1@{ shape: hex, label: Can access the target service from the public network}
  s2.2@{shape: hex, label: The email address send from }
  s3.1[Raise an email to _siteops\@insuremo.com_, and we will share an account to you]
  s3.2[Fill the table below and raise an email to _siteops\@insuremo.com_. We will help you verify the email sender in aws ses]
  
  s9.1[Fill your information on the console and test sending emails]
  s9.2[You can find an email account _xxx\@insuremo.com_ on the console. Test sending emails.]
  s9.3[We will send credentials to your after verifying. Fill the information on the console and test sending emails]

  s1 -- Yes --> s2.1 -- Yes --> s9.1
  s2.1 -- No --> s2.2 -- xxx\@insuremo.com --> s3.1 --> s9.2
  s1 -- No --> s2.2 -- xxx\@your-domain.com --> s3.2 --> s9.3

```

If you need to apply for an email sender of your own domain with aws ses, the following table shows the information you need to fill in.

| Title                              | Example                              | Description                                                       |
| ---------------------------------- | ------------------------------------ | ----------------------------------------------------------------- |
| **Project Code**                   | *1234567 XXX project*                |                                                                   |
| **Email Sender Address / @Domain** | xxx\@insuremo.com / @your-domain.com | The email address you want to send from                           |
| **Site / Env**                     | ptdev                                | The site or environment that the email will send from             |
| **Type of email**                  | Send to policy holder after issuing  | Briefly describe the type of email your will send                 |
| **Quotas**                         | 100 emails per day                   | Expect number of emails sent per day                              |
| **Other requirements**             | None                                 | Such as configuration set rules, DKIM, SPF, specify the region... |

<div class="docs-note"><span class="docs-admonitions-text">note</span> 

If you need to add configurations such as DKIM or SPF to prevent being identified as spam by the recipient, please verify your domain.

</div>

## Basic UI Operations

### Entrance  
1. Log in to [insureMO Portal](https://visitor.insuremo.com/#/home) with your personal account.  

<div class="docs-tip"><span class="docs-admonitions-text">tip</span>  

If you don't have insureMO personal account, click **Sign Up** to register one. Then log in to the portal.  

</div>  

2. Click **Catalog** at the top of the home page.  

3. In the left panel of the **Catalog** page, navigate to **Non Insurance Services** > **Communications**.   

4. Find **EMail Service** card. You will see **API Details** and **Settings**.  
   ![email-card](./image/email/email-card-new.png)    
   a. **API Details** will give you direct access to the APIs listed in it.  
   ![api-details](./image/email/api-details-new.png)    
   b. For creation and other actions, you need to click **Setting** to go to the **Email Management** page.    
   ![email-setting](./image/email/email-setting-new.png)  
   c. This will navigate to the main email settings page where you can manage the service.    
   ![email-page](./image/email/email-page-new.png)

### Account Management 

#### Create

- Click **Create** on the email service console.

![account-create_01](./image/email/account-create-new_01.png)

- Register your email account. Click **Submit**. It will be saved and appear in the list in the main page.

![account-create_02](./image/email/account-create-new_02.png)

#### Edit

- Click **Edit** on the email service console.

![account-edit](./image/email/account-edit-new.png)

#### Delete

- Click **Delete** against a particular record to delete the account.

![account-delete](./image/email/account-delete-new.png)

<div class="docs-note"><span class="docs-admonitions-text">note</span>  

**After confirming deletion, the account will not continue to be used. Before deleting the account, make sure that the account is no longer used by the application.** 

</div>

#### Share

- Click **Share** to share the current configuration of email account operator with other tenants.

![account-share_01](./image/email/account-share-new_01.png)

![account-share_02](./image/email/account-share-new_02.png)

<!-- #### Import and Export

- You can import an email account by clicking **Import Account**. You need to upload the relevant document by selecting the file from the browser and clicking **Confirm** in the overlay.

![account-import&export_01](./image/email/account-import&export_01.png)

- After importing the file, the following window will appear.

![account-import&export_02](./image/email/account-import&export_02.png)

- You get all the records in a text file by clicking **Export Account** on the email service console.

![account-import&export_03](./image/email/account-import&export_03.png) -->

#### Test

- After the account is created successfully, you can verify whether the current account is available through a test email. If available, the receiver will receive the following test email.

![account-test_01](./image/email/account-test-new_01.png)

![account-test_02](./image/email/account-test-new_02.png)

![account-test_03](./image/email/account-test_03.png)

### Blacklist Management

The blacklist stops emails from being sent to specific recipients. It applies to every email the tenant sends, whichever account or sender is used. A platform-wide blacklist maintained by insureMO is also applied on top of the tenant's own list.

![blacklist-page](./image/email/blacklist-page-new.png)

#### How It Works

- Each recipient in `to`, `cc` and `bcc` is checked against the blacklist before sending. Matched recipients are **removed silently**, and the email is still sent to the remaining recipients.
- If no recipient is left after the check, the request fails and nothing is sent.
- Removed recipients are recorded in the email send log.
- Changes to the blacklist take effect within **1 minute**.

#### Match Types

| Match Type     | Matches                                                                                           | Example                  |
| -------------- | ------------------------------------------------------------------------------------------------- | ------------------------ |
| **Whole Word** | The whole address exactly. The comparison is case-sensitive.                                      | `john@example.com`       |
| **Path Match** | A wildcard pattern: `*` matches any characters, `?` matches a single character.                  | `*@example.com`          |
| **Regex**      | A regular expression ([RE2 syntax](https://github.com/google/re2/wiki/Syntax)). A match anywhere in the address counts, so use `^` and `$` to match the whole address. | `^.+@(test\|demo)\.com$` |

<div class="docs-caution"><span class="docs-admonitions-text">caution</span>

A regex without `^` and `$` matches part of an address. For example, `test` blocks `test@example.com` and also `contest@example.com`.

</div>

#### Create

- Click **Create** on the **Blacklist** management page, select the **Match Type**, enter the address or pattern, and click **Submit**.

![blacklist-create_01](./image/email/blacklist-create-new_01.png)

![blacklist-create_02](./image/email/blacklist-create-new_02.png)

#### Delete

- Click **Delete** to remove an entry from the blacklist. Entries cannot be edited. To change one, delete it and create it again.

![blacklist-delete](./image/email/blacklist-delete-new.png)

### Template Management

A template stores the subject and body of an email under a **Template Code**. When sending, pass `template_code` and `template_params` instead of `subject` and `content`, and the service fills in the variables.

![template-page](./image/email/template-page-new.png)

#### Create

- Click **Create** on the **Template** management page, fill in the fields below, and click **Submit**.

![template-create_01](./image/email/template-create-new_01.png)

![template-create_02](./image/email/template-create-new_02.png)

| Field                   | Required | Description                                                                                                                   |
| ----------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
| **Template Code**       | Yes      | Unique within the tenant. Used as `template_code` when sending.                                                               |
| **Template Engine**     | No       | The syntax for variables. See [Template Engines](#template-engines).                                                          |
| **Content Type**        | No       | `text/html` (default), `text/plain`, or `multipart/alternative`.                                                              |
| **Subject**             | No       | Supports variables. If empty, the `subject` must be passed when sending.                                                      |
| **Content**             | Yes      | The email body. Supports variables.                                                                                           |
| **Alternative Content** | Yes, if the content type is `multipart/alternative` | The plain-text version of the body, shown by email clients that do not display HTML. |

The template is checked for syntax errors when it is saved.

#### Template Engines

| Engine          | Variable Syntax  | Notes                                                                                                                         |
| --------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| **Handlebars**  | `{{ variable }}` | [Handlebars](https://handlebarsjs.com/guide/) syntax, including `{{#if}}` and `{{#each}}`. HTML in values is escaped.          |
| **Go Template** | `{{ .variable }}` | [Go template](https://pkg.go.dev/text/template) syntax with [Sprig](https://masterminds.github.io/sprig/) functions. In HTML content, values are escaped. |
| **Simple**      | `${variable}`    | Plain replacement only. A variable that is not passed stays in the email as `${variable}`.                                    |

Example with the **Simple** engine:

```text
Subject:  Policy ${policy_no} has been issued
Content:  <p>Dear ${name},</p><p>Your policy ${policy_no} is now in force.</p>
```

Send request:

```json
{
  "template_code": "policy_issued",
  "template_params": {
    "name": "John",
    "policy_no": "P20260001"
  },
  "to": ["john@example.com"]
}
```

<div class="docs-note"><span class="docs-admonitions-text">note</span>

- `template_params` is **not** recorded in audit logs, so it can carry personal data. Parameters that should be recorded belong in `sender_params`.
- A `subject` in the send request overrides the template subject.
- If the send request sets `content_type`, it must match the template's content type.

</div>

#### Edit and Delete

- Click **Edit** to change a template. The Template Code cannot be changed.
- Click **Delete** to remove a template. Requests that still use its code will fail. Make sure no application still uses the template before deleting it.

#### Import and Export

- **Export** downloads templates as a JSON file: all templates, the current page, or the selected rows.
- **Import** uploads such a JSON file, for example to copy templates from one environment to another. A template with the same Template Code is **overwritten**.

### Log

• You can view the log files in the Audit Service, they are available for a particular day and can be downloaded as well. This is required for audit purpose and to check if there is any issue in the service.

![log-page](./image/email/log-page-new.png)

## Developing with Email Service

### Send Email

#### Calling REST APIs

For all API list, see [insureMO API Reference - email](https://docs.insuremo.com/tech/pro/sdk/api/sns).

After the mail account is configured by the tenant, the tenant can call the API to send emails.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

**Restriction Description**

- We will monitor the content of emails sent by users to prevent it from violating the requirements of national laws and regulations.

- If the message content violates the rules, the relevant users will be frozen. After the account is frozen, the user cannot continue to use the mail service.

</div>

> Authentication
> 

HTTP Authentication, scheme: bearer

<a id="opIdSendEmail"></a>

> POST SendEmail
> 

|                                         API URL                                          | Method |
| :--------------------------------------------------------------------------------------: | :----: |
| [https://\[HOST\]/mo-fo/1.0/sns/email/send](https://[host]/mo-fo/1.0/sns/email/send) |  POST  |

- Header

|   Parameter   |                Value                 |
| :-----------: | :----------------------------------: |
| Authorization | Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXX |

> Body Parameters
> 

```json
{
  "account_name": "insuremo@insuremo.com",
  "alias": "insureMO",
  "attachments": [
    {
      "content": "string",
      "content_id": "string",
      "headers": {
        "property1": "string",
        "property2": "string"
      },
      "mime_type": "string"
    }
  ],
  "auto_format_html": false,
  "bcc": [
    "sample@insuremo.com"
  ],
  "cc": [
    "sample@insuremo.com"
  ],
  "content": "string",
  "content_type": "text/html",
  "custom_headers": {
    "property1": "string",
    "property2": "string"
  },
  "priority": false,
  "reply_to": "string",
  "sender_params": {
    "property1": "string",
    "property2": "string"
  },
  "subject": "Email Service Testing Email",
  "template_code": "string",
  "template_params": {
    "property1": "string",
    "property2": "string"
  },
  "to": [
    "sample@insuremo.com"
  ]
}
```

> Response Examples
> 

If the code is "i_common_success", it indicates successful sending. Otherwise, the sending fails.

```json
{
  "code": "i_common_success",
  "data": {
    "content_length": 0,
    "data": "string",
    "message_id": "string"
  },
  "message": "string",
  "message_params": [
    "string"
  ],
  "trace_id": "string"
}
```

#### Using insureMO Email SDK For Java

Please refer to this document: [Welcome to insureMO SDK for Java](https://docs.insuremo.com/common/doc_00000089).

Code example:

```java
import com.insuremo.sdk.core.exception.ApiException;
import com.insuremo.sdk.services.sns.SnsSdkClient;
import com.insuremo.sdk.services.sns.api.EmailApi;
import com.insuremo.sdk.services.sns.bundle.SendEmailResponseBundle;
import com.insuremo.sdk.services.sns.model.SendEmailRequest;

public class EmailApi_sendEmail {

    public static void main(SnsSdkClient snsSdkClient) {
        System.out.println("----- Example for EmailApi.sendEmail -----");
        EmailApi emailApi = snsSdkClient.emailApi();

        System.out.println("----- sendEmail -----");

        try {
            SendEmailResponseBundle responseBundle = emailApi.newSendEmailRequestBuilder()
                    .sendEmailRequest(new SendEmailRequest().
                            accountName("portal-test@insuremo.com").
                            subject("email testing").
                            content("This is a testing email").
                            addToItem("sdk-test@simulator.insuremo.com"))
                    .doRequest();
            System.out.println(responseBundle.getBody().getData());
        } catch (ApiException e) {
            System.out.println(e.getResponseBody());
            System.out.println(e.getCode());
        }
        System.out.println("----- Done. -----");
    }
}
```

### Send 2FA Email (Verify Code)

Please see [Send An MFA Code via Email](https://docs.insuremo.com/common/doc_00000305#developing-with-email-mfa-api).

### Migrate to SNS API

#### Send Email

##### API:

`https://[host]/eBao/1.0/email/send` 

=>

`https://[host]/mo-fo/1.0/sns/email/send`

##### Request Body:

| /eBao/1.0/email/send            | /mo-fo/1.0/sns/email/send          | Data Type    | Difference                                                                                              |
| ------------------------------- | --------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------- |
| account                         | account_name                      | string       |                                                                                                         |
| alias                           | alias                             | string       |                                                                                                         |
| attachment                      | attachments                       | array/Object |                                                                                                         |
| attachment.attachmentContent    | attachments.content               | string/byte  |                                                                                                         |
| attachment.attachmentMimeType   | attachments.mime_type             | string       |                                                                                                         |
| attachment.attachmentName       | attachments.content_id            | string       |                                                                                                         |
| autoformat                      | -                                 | bool         | Deperated field. You should specify email content type as html(default) or text and format the content. |
| bcc                             | bcc                               | array/string |                                                                                                         |
| cc                              | cc                                | array/string |                                                                                                         |
| consignee                       | to                                | array/string |                                                                                                         |
| content                         | content                           | string       |                                                                                                         |
| contentType                     | content_type                      | string       |                                                                                                         |
| contentFiles                    | attachments                       | array/Object | Same as attachment                                                                                      |
| contentFiles.attachmentContent  | attachments.content               | string/byte  |                                                                                                         |
| contentFiles.attachmentMimeType | attachments.mime_type             | string       |                                                                                                         |
| contentFiles.contentId          | attachments.content_id            | string       |                                                                                                         |
| contentFiles.headers            | attachments.headers               | map/string   |                                                                                                         |
| customHeaders                   | custom_headers                    | map/string   |                                                                                                         |
| priority                        | priority                          | bool         |                                                                                                         |
| replyto                         | reply_to                          | string       |                                                                                                         |
| subject                         | subject                           | string       |                                                                                                         |
| templateCode                    | template_code                     | string       |                                                                                                         |
| templateParams                  | template_params<br/>sender_params | map/string   |     Split into two different parameters.<br/>`template_params` is used for value replacement in templates and **will not be** recorded in audit logs.<br/>`sender_params` specifies the parameters for sending the email and **will be** recorded in audit logs.                |

##### Response:

`/eBao/1.0/email/send` 

Success Response:

HTTP Status Code: 200

```json
{
    "body": "abcd1234-ab12-cd34-ac13-abcd1234abcd",
    "info": "abcd1234-ab12-cd34-ac13-abcd1234abcd",
    "status": 0
}
```

Failed Response:

HTTP Status Code: 200

```json
{
    "body": null,
    "info": "error message",
    "message": "error message",
    "status": 1
}
```

=>

`/mo-fo/1.0/sns/email/send`

Success Response:

HTTP Status Code: 200

```json
{
  "code": "i_common_success",
  "data": {
    "content_length": 0,
    "data": "string",
    "message_id": "string"
  },
  "trace_id": "string"
}
```

Failed Response:

HTTP Status Code: 499 / 599

```json
{
  "code": "e_sns_email_error_code",
  "message": "string",
  "message_params": [
    "string"
  ],
  "trace_id": "string"
}
```

## FAQs

### Q: What email can I send?

A: Triggered email: Emails triggered by events, such as registration notification, transaction notification, and verification notification emails.

Batch email: Subscription emails sent to members, such as product promotion, user notification, periodical information. The email service only allows sending commercial emails permitted by the recipient. The mail content is the recipient's active subscription. The unlicensed spam is not allowed to be sent.

### Q: Can the attachments be added to email?

A: Yes, see API interface for more details.

### Q: Why did all the emails go into the recipient's junk mailbox?

A: It's generally because the email content is judged as spam by the recipient's system. Attempts can be made to adjust the email content and avoid the use of spam terms. Then send a test email to your other mailboxes to check if the new content is still considered as spam.

### Q: Suggestions on Spam Handling

A: Standardize the email content and use the link address of website. Avoid using short link address. Otherwise, it will be regarded as spam.

Add the address of the unsubscribe link to the email content and perform the actual unsubscribe. At the same time, remind the recipient to add the sender's address to the whitelist or to contact at a clear location. At the same time, add the introduction of your company and products.

If the sender sends the same message to multiple recipients at the same time, it may also be automatically identified as spam by the system.