> For the complete documentation index, see [llms.txt](https://tech.x2bee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tech.x2bee.com/dev-guide/developer-guide-en/dev-start/customer-message-sending/email-sending.md).

# Email Sending

This document covers the email sending source code and method.

First, it explains how to configure and verify the Config settings.\
Second, it explains how to write it at each business layer.

{% hint style="info" %}
\<update>

2023.08.03

* Modified so that MailSendRequest works automatically even if siteNo is not entered.

2024.05.29

* Added sendTemplateMailBulk
  {% endhint %}

***

## Config Settings

**application.yml**

```yaml
mail:
  smtp:
    host: smtp.office365.com
    port: 587
    userName: x2bee@plateer.com
    password: X2commerce!1
  fromMail: x2bee@plateer.com
  fromNameKo: 플래티어_X2BEE
  fromNameEn: PLATEER_X2BEE
```

## Sample Source and Description

* [x2bee-api-sample-vanilla](https://gitlab.x2bee.com/x2bee-venus-beta/venus-x2bee-api-sample-vanilla) project

**MailController Example (Summary):**

```java
@Autowired
private MailSender mailSender;

@PostMapping("/send")
public ResponseEntity<Response> send() throws MessagingException, UnsupportedEncodingException {
    Map<String, Object> params = new HashMap<>();
    // 템플릿용 파라미터
    params.put("name","teset");

    // 단건 전송
    MailSendRequest request = MailSendRequest.builder()
        .siteNo("1") // null 일 경우 Cookie에서 자동입력됩니다.
        .mbrNo("100033")
        .emailGbCd("EMA-MA_11")
        .emailTitle("안녕하세요 이메일 전송 테스트입니다.")
        .emailConts("이메일 내용이 들어가는 곳입니다.") // 템플릿을 사용하는경우 삭제!
        .template("sample/sp1") // 템플릿을 사용하는 경우 ---(2)필독!
        .variables(params) // 템플릿용 파라미터
        .recvmnNm("테스트")
        .recvmnEmailAddr("emailtempid@naver.com")
        .build();

    // ----- API-COMMON 프로젝트에서 직접 호출시
    mailSender.send(request);

    // ----- API-COMMON 호출시
    // restApiUtil.post(
    //   this.commonApiUrl + "/api/common/interface/bizmessage/sendmail",
    //   request,
    //   new ParameterizedTypeReference<Response<Void>>() {}
    // ).getPayload();

    // 대량 전송 예시
    List<MailSendRequest> mailSendRequestList = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        mailSendRequestList.add(
            MailSendRequest.builder()
                .siteNo("1") // null 일 경우 Cookie에서 자동입력됩니다.
                .mbrNo("100033")
                .emailGbCd("EMA-MA_11")
                .emailTitle("안녕하세요 이메일 전송 테스트 : "+(i+1))
                .emailConts("이메일 내용이 들어가는 곳입니다. -- "+(i+1)) // 템플릿을 사용하는경우 삭제!
                .template("sample/sp1") // 템플릿을 사용하는 경우 ---(2)필독!
                .variables(params) // 템플릿용 파라미터
                .recvmnNm("테스트")
                .recvmnEmailAddr("emailtempid@naver.com")
                .build()
        );
    }

    // ----- API-COMMON 프로젝트에서 직접 호출시
    // mailSender.sendBulk(mailSendRequestList);

    // ----- API-COMMON 호출시
    // restApiUtil.post(
    //   this.commonApiUrl + "/api/common/interface/bizmessage/sendmailbulk",
    //   mailSendRequestList,
    //   new ParameterizedTypeReference<Response<Void>>() {}
    // ).getPayload();

    ...
}
```

<kbd>MailSendRequest</kbd> Create a <kbd>MailSendRequest</kbd> and enter the parameters by referring to the example and the table below.

| Item            | Mandatory              | Type   | Description                       | Notes                                                         |
| --------------- | ---------------------- | ------ | --------------------------------- | ------------------------------------------------------------- |
| siteNo          | NOT NULL (auto-filled) | String | Site number                       | Automatically filled from the cookie value if entered as null |
| mbrNo           | NOT NULL               | String | Member number                     |                                                               |
| emailGbCd       | NOT NULL               | String | Email classification code (CM030) |                                                               |
| emailTitle      | NOT NULL               | String | Email subject                     |                                                               |
| emailConts      | NOT NULL               | String | Email content                     |                                                               |
| recvmnNm        | NOT NULL               | String | Recipient name                    |                                                               |
| recvmnEmailAddr | NOT NULL               | String | Recipient email address           |                                                               |

**If you're not familiar with Builder, you can also use Setter:**

```java
MailSendRequest mailSendRequest = new MailSendRequest();
...
mailSendRequest.setEmailTitle("이메일 제목");
mailSendRequest.setEmailConts("이메일 내용");
mailSendRequest.setRecvmnEmailAddr("plateer@plateer.com");
...
mailSender.send(mailSendRequest);
```

### sendBulk Added

* A sendBulk method has been added that sends a large number of messages at once.
* Available from `X2BEE-COMMON 0.6.3` onward
  * Processes email sending by receiving a List of `MailSendRequest` objects.
  * Process: INSERT the mail-sending list (synchronous), process mail sending (asynchronous)
  * Table.Column name: ST\_EMAIL\_SND\_HIST.email\_trns\_stat\_cd\
    (`CM029`) – Send success: 30 → <mark style="color:$success;">Sent</mark>, Send failure: 20 → <mark style="color:$danger;">Send ERROR</mark>

1. **When Sending Email from Another Project (Calling api-common)**

* **If sending email from a project other than `x2bee-api-common-vanilla`, call the api-common API.**
* As shown in the example source, put the required parameters into a `MailSendRequest` object and call the `/api/common/interface/bizmessage/sendmail` endpoint using the POST method.
* `commonApiUrl` is the URL specified in application.yml.

2. **When Using a Template (Must Read)**

* As the MailSender that used to be in each project was moved to Common, the Thymeleaf templates that were in each project were also moved together to `x2bee-api-common-vanilla`.
* Therefore, when creating a new template, you must place it in the path corresponding to each project's folder.

<figure><img src="https://200425-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVEZx3rsZsIv89GPS3d2J%2Fuploads%2FHVlRlBJiPEG0uKgMrswX%2Fimage.png?alt=media&#x26;token=52b40d35-54e7-4c49-9b98-a58cf73661e4" alt="" width="375"><figcaption></figcaption></figure>

* **The template path (`email/apibo`, `email/apidisplay`, etc.) is specified in each project's `application.yml`, and is automatically prepended to the template variable string in Builder and Setter.**
* Therefore, when specifying a template, enter the path starting after `email/apibo`.

  * ex) application.yml within the x2bee-api-display-vanilla project
  *

  ```
  <div align="left"><img src="https://tech.x2bee.com/download/attachments/108003385/image-20230719-051634.png?version=1&#x26;modificationDate=1689743799588&#x26;cacheVersion=1&#x26;api=v2" alt="" width="375"></div>
  ```

***

### sendTemplateMailBulk Added

* Unlike the existing mail API, sendTemplateMailBulk has been added, which sends mail by receiving template data as a top-level parameter.
* Available from `X2BEE-COMMON 0.9.71` onward
* As before, you can use it by entering a template file path, or by sending template data as a string.

### Sample Source — sendTemplateMailBulk

Example when using a template file path:

```java
MailSendTemplateRequest mailSendTemplateRequest = new MailSendTemplateRequest();
mailSendTemplateRequest.setTemplate("email/apimember/Join_ko");
mailSendTemplateRequest.setMailList(mailSendRequestList);

restApiUtil.post(
  this.commonApiUrl + "/api/common/interface/bizmessage/sendTemplateMailBulk",
  mailSendTemplateRequest,
  new ParameterizedTypeReference<Response<Void>>() {}
).getPayload();
```

Example when using a template string:

```java
MailSendTemplateRequest mailSendTemplateRequest = new MailSendTemplateRequest();
mailSendTemplateRequest.setTemplate("<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8' /><title>회원가입완료 안내</title></head><body><tbody><td>[<span th:text='${userName}'></span>]님, 안녕하세요.<br />[<span th:text='${userName}'></span>]님의 회원가입을 진심으로 감사드립니다.</td></tbody></table></body></html>");
mailSendTemplateRequest.setMailList(mailSendRequestList);

restApiUtil.post(
  this.commonApiUrl + "/api/common/interface/bizmessage/sendTemplateMailBulk",
  mailSendTemplateRequest,
  new ParameterizedTypeReference<Response<Void>>() {}
).getPayload();
```

***
