Java Mail Dispatch via HTTP Client and JSON Payload
The fololwing demonstrates how to trigger email notifications by calling a remote messaging endpoint 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());
}
}
}
}
Configuratoin
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><table>")
.append("<tr><th>Req No</th><th>Code</th><th>Model</th><th>Qty</th></tr>");
for (MaterialRequestVO vo : requestList) {
html.append("<tr>")
.append("<td>").append(vo.getRequestNo()).append("</td>")
.append("<td>").append(vo.getCode()).append("</td>")
.append("<td>").append(vo.getModel()).append("</td>")
.append("<td>").append(vo.getQuantity()).append("</td>")
.append("</tr>");
}
html.append("</table></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) + "]");