使用第三方接口实现邮件发送

package com.chint;

import com.google.gson.Gson;
import jdk.internal.org.xml.sax.InputSource;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@SpringBootTest
class SsoApplicationTests {

    @Test
    void contextLoads() throws Exception {
        String publishUrl = "第三方的接口地址";
        SendEmailHelper sendEmailHelper = new SendEmailHelper(publishUrl);
        MsgJson msgJson = new MsgJson();
        msgJson.setTitle("标题");
        msgJson.setBody("");
        msgJson.setHtmlBody("");
        msgJson.setUrl("");
        msgJson.setFrom("");
        msgJson.setSender("");

        UserJson userJson = new UserJson();
        userJson.setEmail("发给谁");
        userJson.setAppid(""); // 设置 appid 值
        sendEmailHelper.sendEmail(msgJson, userJson);

    }


    public class SendEmailHelper {
        private final String publishUrl;

        public SendEmailHelper(String publishUrl) {
            this.publishUrl = publishUrl;
        }

        public String sendEmail(MsgJson msgJson, UserJson userJson) throws IOException {
            String str = "userJson=" + new Gson().toJson(userJson) + "&msgJson=" + new Gson().toJson(msgJson);
            String result = httpPostForm2(publishUrl, str);
            return result;
        }

        //使用的是HttpURLConnection 方式
        public String httpPostForm(String url, String data) throws IOException {
            boolean success = false;
            String htmlAll = "";
            try {
                String sendMessageAddress = url;
                URL requestUrl = new URL(sendMessageAddress);
                HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
                connection.setRequestMethod("POST");
                connection.setInstanceFollowRedirects(true);
                connection.setConnectTimeout(20 * 1000);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("x-cherun-auth-key", "LarxMbndsxfGwoYAqsfJSPPU42l04cb3");

                byte[] postDataBytes = data.getBytes("UTF-8");
                connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                connection.setDoOutput(true);

                try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
                    outputStream.write(postDataBytes);
                    outputStream.flush();
                }

                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                htmlAll = response.toString();
                connection.disconnect();
            } catch (IOException ex) {
                // Handle exception
            }

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document document = builder.parse(String.valueOf(new InputSource(new StringReader(htmlAll))));
                Element rootElement = document.getDocumentElement();
                success = Boolean.parseBoolean(rootElement.getChildNodes().item(0).getTextContent());
            } catch (Exception ex) {
                // Handle exception
            }

            return String.valueOf(success);
        }
    }

   //使用的是CloseableHttpClient方式
    public String httpPostForm2(String url, String data) throws IOException {
        String success = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setHeader("x-cherun-auth-key", "LarxMbndsxfGwoYAqsfJSPPU42l04cb3");

            StringEntity requestEntity = new StringEntity(data, StandardCharsets.UTF_8);
            httpPost.setEntity(requestEntity);

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            EntityUtils.toString(responseEntity, "UTF-8");
            if (statusCode == 200){
                success = String.valueOf(response.getStatusLine().getStatusCode());
            }else {
                return String.valueOf(response.getStatusLine().getStatusCode());
            }

        } finally {
            httpClient.close();
        }

        return success;
    }

    class MsgJson {
        private String Title;
        private String Body;
        private String HtmlBody;
        private String Url;
        private String From;
        private String Sender;

        public String getTitle() {
            return Title;
        }

        public void setTitle(String title) {
            Title = title;
        }

        public String getBody() {
            return Body;
        }

        public void setBody(String body) {
            Body = body;
        }

        public String getHtmlBody() {
            return HtmlBody;
        }

        public void setHtmlBody(String htmlBody) {
            HtmlBody = htmlBody;
        }

        public String getUrl() {
            return Url;
        }

        public void setUrl(String url) {
            Url = url;
        }

        public String getFrom() {
            return From;
        }

        public void setFrom(String from) {
            From = from;
        }

        public String getSender() {
            return Sender;
        }

        public void setSender(String sender) {
            Sender = sender;
        }
        // Getters and setters
    }

    class UserJson {
        private String Email;
        private String Appid;

        public String getEmail() {
            return Email;
        }

        public void setEmail(String email) {
            Email = email;
        }

        public String getAppid() {
            return Appid;
        }

        public void setAppid(String appid) {
            Appid = appid;
        }
        // Getters and setters
    }

    class PersonDto {
        private String LeaveName;
        private String SendEmail;

        public String getLeaveName() {
            return LeaveName;
        }

        public void setLeaveName(String leaveName) {
            LeaveName = leaveName;
        }

        public String getSendEmail() {
            return SendEmail;
        }

        public void setSendEmail(String sendEmail) {
            SendEmail = sendEmail;
        }
// Getters and setters
    }


}
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值