package com.gear.common.utils.email; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class SendEmailUtils { public static boolean sendEmial(Emailer sender,Emailer[] to,String title,String content){ String key = "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"; try { // 创建URL对象 URL url = new URL("https://api.brevo.com/v3/smtp/email"); // 打开连接,并将URLConnection转换为HttpURLConnection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为POST connection.setRequestMethod("POST"); // 设置请求头参数 connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("accept", "application/json"); connection.setRequestProperty("api-key", key); // 启用输出流,以便向服务器发送数据 connection.setDoOutput(true); JSONObject param = new JSONObject(); param.put("sender",sender); param.put("to",to); param.put("subject",title); param.put("htmlContent",content); System.out.println("params:"+ param.toString()); // 将JSON数据写入请求体 try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { byte[] input = param.toString().getBytes("utf-8"); wr.write(input, 0, input.length); } // 发送请求 int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); if (responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK) { // 读取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuffer response = new StringBuffer(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 打印响应内容 System.out.println("Response: " + response.toString()); return true; } else { // 错误处理或其他逻辑 System.out.println("Error: " + responseCode); } // 关闭连接 connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } return false; } }