Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Mail Dispatch via HTTP Client and JSON Payload

Tech May 8 53

The following demonstrates how to trigger email notifications by calling a remote messaging enpdoint using RestTemplate and JSON serialization.

Service Method

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Component
public class TaskNotifier {

    @Value("${notify.mail.endpoint}")
    private String mailApi;

    @Value("${notify.mail.sender}")
    private String senderAddress;

    private final HttpClientService httpClient;

    public TaskNotifier(HttpClientService httpClient) {
        this.httpClient = httpClient;
    }

    public void notifyTaskStopped(ScheduleTaskVO taskInfo) {
        Map<String, Object> payload = new HashMap<>(8);

        String timestamp = LocalDateTime.now()
                                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        payload.put("subject", "Scheduled Task Alert");
        payload.put("from", senderAddress);
        payload.put("to", taskInfo.getTargetEmail());
        payload.put("html", false);
        payload.put("content", String.format(
            "Hello, the scheduled task [%s] was automatically stopped at %s. Please investigate.",
            taskInfo.getName(), timestamp
        ));

        String jsonBody = "[" + JSON.toJSONString(payload) + "]";
        ApiResponse<String> result = httpClient.post(mailApi, jsonBody);

        if (result != null && "200".equals(result.getCode())) {
            JSONArray successList = JSON.parseObject(result.getData()).getJSONArray("successIds");
            if (successList.isEmpty()) {
                log.warn("Email delivery failed for task: {}", taskInfo.getName());
            }
        }
    }
}

Configuration

notify:
  mail:
    endpoint: ${api-gateway}/notify/email
    sender: alert@company.com

Response Model

import lombok.Data;
import java.io.Serializable;

@Data
public class ApiResponse<T> implements Serializable {
    private String code;
    private String message;
    private T data;

    public static <T> ApiResponse<T> success(T body) {
        ApiResponse<T> res = new ApiResponse<>();
        res.setCode("200");
        res.setMessage("OK");
        res.setData(body);
        return res;
    }

    public static <T> ApiResponse<T> error(String msg) {
        ApiResponse<T> res = new ApiResponse<>();
        res.setCode("500");
        res.setMessage(msg);
        return res;
    }
}

HTTP Client Utility

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class HttpClientService {

    private final RestTemplate restTemplate;

    public HttpClientService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public ApiResponse<String> post(String url, String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> request = new HttpEntity<>(json, headers);
        ResponseEntity<String> response = restTemplate.exchange(
            url, HttpMethod.POST, request, String.class
        );

        if (response.getStatusCode().is2xxSuccessful()) {
            return ApiResponse.success(response.getBody());
        }
        return ApiResponse.error(response.getBody());
    }
}

HTML Table Email Example

StringBuilder html = new StringBuilder();
html.append("<html><head><meta charset='UTF-8'><style>")
    .append("table {border-collapse: collapse; width: 100%;}")
    .append("td, th {border: 1px solid #ddd; padding: 8px;}")
    .append("th {background-color: #f4f4f4;}</style></head><body>")
    .append("<p>Hello,</p><p>Material replenishment details:</p>| Req No | Code | Model | Qty |
|---|---|---|---|
| ").append(vo.getRequestNo()).append(" | ").append(vo.getCode()).append(" | ").append(vo.getModel()).append(" | ").append(vo.getQuantity()).append(" |</body></html>");

Map<String, Object> mail = new HashMap<>();
mail.put("subject", "Material Purchase Notification");
mail.put("from", senderAddress);
mail.put("to", recipient);
mail.put("html", true);
mail.put("content", html.toString());

httpClient.post(mailApi, "[" + JSON.toJSONString(mail) + "]");

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.