蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Java 8 RFC 5322 多收件人、MIME Base64 附件与本地回环 SMTP 认证协议实测

JAVAWindows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。ExploreSendingEmail.java
ExploreSendingEmail.java388 行
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;

public class ExploreSendingEmail {
    private static String buildRfc5322Plain(String from, List<String> to, List<String> cc, String subject, String body) {
        StringBuilder sb = new StringBuilder();
        sb.append("From: ").append(sanitizeHeader(from)).append("\r\n");
        sb.append("To: ").append(String.join(", ", to)).append("\r\n");
        if (!cc.isEmpty()) {
            sb.append("Cc: ").append(String.join(", ", cc)).append("\r\n");
        }
        sb.append("Subject: ").append(sanitizeHeader(subject)).append("\r\n");
        sb.append("MIME-Version: 1.0\r\n");
        sb.append("Content-Type: text/plain; charset=UTF-8\r\n");
        sb.append("\r\n");
        sb.append(body).append("\r\n");
        return sb.toString();
    }

    private static String sanitizeHeader(String value) {
        if (value.indexOf('\r') >= 0 || value.indexOf('\n') >= 0) {
            throw new IllegalArgumentException("Header value must not contain CR/LF");
        }
        return value;
    }

    private static String buildMultipartEmail(String from, String to, String subject, String htmlPart, String fileName, byte[] fileBytes) {
        String boundary = "----=_Part_BlueSky_001";
        String encoded = Base64.getMimeEncoder(76, new byte[]{'\r', '\n'}).encodeToString(fileBytes);
        StringBuilder sb = new StringBuilder();
        sb.append("From: ").append(sanitizeHeader(from)).append("\r\n");
        sb.append("To: ").append(sanitizeHeader(to)).append("\r\n");
        sb.append("Subject: ").append(sanitizeHeader(subject)).append("\r\n");
        sb.append("MIME-Version: 1.0\r\n");
        sb.append("Content-Type: multipart/mixed; boundary=\"").append(boundary).append("\"\r\n\r\n");
        sb.append("--").append(boundary).append("\r\n");
        sb.append("Content-Type: text/html; charset=UTF-8\r\n\r\n");
        sb.append(htmlPart).append("\r\n");
        sb.append("--").append(boundary).append("\r\n");
        sb.append("Content-Type: application/octet-stream; name=\"").append(fileName).append("\"\r\n");
        sb.append("Content-Transfer-Encoding: base64\r\n");
        sb.append("Content-Disposition: attachment; filename=\"").append(fileName).append("\"\r\n\r\n");
        sb.append(encoded).append("\r\n");
        sb.append("--").append(boundary).append("--\r\n");
        return sb.toString();
    }

    private static String escapeJson(String s) {
        StringBuilder sb = new StringBuilder("\"");
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '"': sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
                    else sb.append(c);
            }
        }
        return sb.append('"').toString();
    }

    private static String toJson(Object obj) {
        if (obj == null) return "null";
        if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
        if (obj instanceof String) return escapeJson((String) obj);
        if (obj instanceof List<?>) {
            StringBuilder sb = new StringBuilder("[");
            List<?> list = (List<?>) obj;
            for (int i = 0; i < list.size(); i++) {
                if (i > 0) sb.append(", ");
                sb.append(toJson(list.get(i)));
            }
            return sb.append("]").toString();
        }
        if (obj instanceof Map<?, ?>) {
            StringBuilder sb = new StringBuilder("{");
            boolean first = true;
            for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
                if (!first) sb.append(", ");
                first = false;
                sb.append(escapeJson(String.valueOf(e.getKey()))).append(": ").append(toJson(e.getValue()));
            }
            return sb.append("}").toString();
        }
        return escapeJson(String.valueOf(obj));
    }

    private static Map<String, Object> makeCase(String name, String summary, Object expected, Object actual) {
        Map<String, Object> c = new LinkedHashMap<String, Object>();
        c.put("name", name);
        c.put("summary", summary);
        c.put("expected", expected);
        c.put("actual", actual);
        c.put("passed", expected.equals(actual));
        return c;
    }

    public static void main(String[] args) throws Exception {
        List<Map<String, Object>> cases = new ArrayList<Map<String, Object>>();

        // Case 1: RFC 5322 plain-text & multi-recipient (TO/CC/BCC) header assembly & CRLF injection guard
        {
            List<String> toList = Arrays.asList("alice@example.com", "bob@example.com");
            List<String> ccList = Arrays.asList("audit@example.com");
            List<String> bccEnvelopeOnly = Arrays.asList("secret@example.com");
            String rawMsg = buildRfc5322Plain(
                "sender@example.com",
                toList,
                ccList,
                "Weekly Status Report",
                "This is actual message"
            );

            boolean crlfBlocked = false;
            try {
                sanitizeHeader("Bad\r\nBcc: attacker@example.com");
            } catch (IllegalArgumentException ex) {
                crlfBlocked = true;
            }

            List<String> smtpRcptEnvelope = new ArrayList<String>();
            smtpRcptEnvelope.addAll(toList);
            smtpRcptEnvelope.addAll(ccList);
            smtpRcptEnvelope.addAll(bccEnvelopeOnly);

            Map<String, Object> expected = new LinkedHashMap<String, Object>();
            expected.put("has_to_and_cc_headers", true);
            expected.put("bcc_omitted_from_visible_headers", true);
            expected.put("envelope_recipient_count", 4);
            expected.put("header_injection_blocked", true);

            Map<String, Object> actual = new LinkedHashMap<String, Object>();
            actual.put("has_to_and_cc_headers",
                rawMsg.contains("To: alice@example.com, bob@example.com\r\n")
                && rawMsg.contains("Cc: audit@example.com\r\n"));
            actual.put("bcc_omitted_from_visible_headers", !rawMsg.contains("secret@example.com"));
            actual.put("envelope_recipient_count", smtpRcptEnvelope.size());
            actual.put("header_injection_blocked", crlfBlocked);

            cases.add(makeCase(
                "rfc5322_headers_and_multi_recipients",
                "验证 RFC 5322 邮件头组装、TO/CC/BCC 可见性与信封收件人隔离及 CRLF 头部注入拦截",
                expected,
                actual
            ));
        }

        // Case 2: HTML & multipart/mixed MIME message with Base64 attachment round-trip
        {
            byte[] fileData = "Invoice #2026-01: Paid".getBytes(StandardCharsets.UTF_8);
            String mime = buildMultipartEmail(
                "billing@example.com",
                "client@example.com",
                "HTML & Attachment Demo",
                "<h1>This is actual message</h1>",
                "file.txt",
                fileData
            );

            String b64 = Base64.getMimeEncoder(76, new byte[]{'\r', '\n'}).encodeToString(fileData);
            String decoded = new String(Base64.getMimeDecoder().decode(b64), StandardCharsets.UTF_8);

            Map<String, Object> expected = new LinkedHashMap<String, Object>();
            expected.put("has_multipart_header", true);
            expected.put("has_html_part", true);
            expected.put("has_attachment_disposition", true);
            expected.put("base64_roundtrip_text", "Invoice #2026-01: Paid");

            Map<String, Object> actual = new LinkedHashMap<String, Object>();
            actual.put("has_multipart_header", mime.contains("Content-Type: multipart/mixed; boundary="));
            actual.put("has_html_part", mime.contains("Content-Type: text/html; charset=UTF-8\r\n\r\n<h1>This is actual message</h1>"));
            actual.put("has_attachment_disposition", mime.contains("Content-Disposition: attachment; filename=\"file.txt\""));
            actual.put("base64_roundtrip_text", decoded);

            cases.add(makeCase(
                "mime_html_and_base64_attachment",
                "验证 HTML 邮件体与 multipart/mixed MIME 边界结构及 Base64 附件编码还原",
                expected,
                actual
            ));
        }

        // Case 3: Real local loopback mock SMTP server/client Socket exchange (220/EHLO/AUTH PLAIN/MAIL FROM/RCPT TO/DATA/QUIT)
        {
            final List<String> serverTranscript = new ArrayList<String>();
            final AtomicReference<String> capturedBody = new AtomicReference<String>("");
            final AtomicReference<Throwable> serverErr = new AtomicReference<Throwable>(null);

            ServerSocket server = new ServerSocket(0, 5, InetAddress.getLoopbackAddress());
            try {
                server.setSoTimeout(5000);
                final int port = server.getLocalPort();
                Thread smtpThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try (Socket conn = server.accept()) {
                            conn.setSoTimeout(5000);
                            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
                            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
                            out.write("220 localhost MockSMTP ready\r\n");
                            out.flush();

                            String line;
                            while ((line = in.readLine()) != null) {
                                if (line.startsWith("EHLO")) {
                                    serverTranscript.add("EHLO");
                                    out.write("250-localhost\r\n250 AUTH PLAIN\r\n");
                                    out.flush();
                                } else if (line.startsWith("AUTH PLAIN ")) {
                                    serverTranscript.add("AUTH");
                                    String token = line.substring("AUTH PLAIN ".length()).trim();
                                    String creds = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8);
                                    if ("\0demo@example.com\0app-auth-code".equals(creds)) {
                                        out.write("235 Authentication succeeded\r\n");
                                    } else {
                                        out.write("535 Authentication failed\r\n");
                                    }
                                    out.flush();
                                } else if (line.startsWith("MAIL FROM:")) {
                                    serverTranscript.add("MAIL_FROM");
                                    out.write("250 OK\r\n");
                                    out.flush();
                                } else if (line.startsWith("RCPT TO:")) {
                                    serverTranscript.add("RCPT_TO");
                                    out.write("250 OK\r\n");
                                    out.flush();
                                } else if ("DATA".equals(line)) {
                                    serverTranscript.add("DATA");
                                    out.write("354 End data with <CRLF>.<CRLF>\r\n");
                                    out.flush();
                                    StringBuilder dataBuf = new StringBuilder();
                                    String dline;
                                    while ((dline = in.readLine()) != null && !".".equals(dline)) {
                                        dataBuf.append(dline).append('\n');
                                    }
                                    capturedBody.set(dataBuf.toString());
                                    out.write("250 Message queued\r\n");
                                    out.flush();
                                } else if ("QUIT".equals(line)) {
                                    serverTranscript.add("QUIT");
                                    out.write("221 Bye\r\n");
                                    out.flush();
                                    break;
                                }
                            }
                        } catch (Throwable t) {
                            serverErr.set(t);
                        }
                    }
                });
                smtpThread.setDaemon(true);
                smtpThread.start();

                List<String> replyCodes = new ArrayList<String>();
                try (Socket client = new Socket("127.0.0.1", port)) {
                    client.setSoTimeout(5000);
                    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
                    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream(), StandardCharsets.UTF_8));

                    replyCodes.add(in.readLine().substring(0, 3)); // 220

                    out.write("EHLO client.local\r\n");
                    out.flush();
                    in.readLine(); // 250-localhost
                    replyCodes.add(in.readLine().substring(0, 3)); // 250

                    String authPayload = Base64.getEncoder().encodeToString("\0demo@example.com\0app-auth-code".getBytes(StandardCharsets.UTF_8));
                    out.write("AUTH PLAIN " + authPayload + "\r\n");
                    out.flush();
                    replyCodes.add(in.readLine().substring(0, 3)); // 235

                    out.write("MAIL FROM:<demo@example.com>\r\n");
                    out.flush();
                    replyCodes.add(in.readLine().substring(0, 3)); // 250

                    out.write("RCPT TO:<target@example.com>\r\n");
                    out.flush();
                    replyCodes.add(in.readLine().substring(0, 3)); // 250

                    out.write("DATA\r\n");
                    out.flush();
                    replyCodes.add(in.readLine().substring(0, 3)); // 354

                    out.write("Subject: Loopback Test\r\n\r\nHello SMTP\r\n.\r\n");
                    out.flush();
                    replyCodes.add(in.readLine().substring(0, 3)); // 250

                    out.write("QUIT\r\n");
                    out.flush();
                    replyCodes.add(in.readLine().substring(0, 3)); // 221
                }
                smtpThread.join(3000);
                if (serverErr.get() != null) {
                    throw new RuntimeException(serverErr.get());
                }

                Map<String, Object> expected = new LinkedHashMap<String, Object>();
                expected.put("smtp_reply_codes", Arrays.asList("220", "250", "235", "250", "250", "354", "250", "221"));
                expected.put("server_commands", Arrays.asList("EHLO", "AUTH", "MAIL_FROM", "RCPT_TO", "DATA", "QUIT"));
                expected.put("payload_contains_body", true);

                Map<String, Object> actual = new LinkedHashMap<String, Object>();
                actual.put("smtp_reply_codes", replyCodes);
                actual.put("server_commands", serverTranscript);
                actual.put("payload_contains_body", capturedBody.get().contains("Hello SMTP"));

                cases.add(makeCase(
                    "loopback_smtp_auth_and_data_exchange",
                    "验证本地回环模拟 SMTP 服务的 220/EHLO/AUTH PLAIN/MAIL FROM/RCPT TO/DATA/QUIT 完整协议交互",
                    expected,
                    actual
                ));
            } finally {
                server.close();
            }
        }

        // Case 4: SMTP Properties configuration & JDK 8 javax.activation built-in check
        {
            Properties props = new Properties();
            props.setProperty("mail.smtp.host", "smtp.example.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            boolean hasJafInJdk8;
            try {
                Class.forName("javax.activation.DataHandler");
                hasJafInJdk8 = true;
            } catch (ClassNotFoundException ex) {
                hasJafInJdk8 = false;
            }

            boolean hasExternalJavaxMail;
            try {
                Class.forName("javax.mail.Session");
                hasExternalJavaxMail = true;
            } catch (ClassNotFoundException ex) {
                hasExternalJavaxMail = false;
            }

            Map<String, Object> expected = new LinkedHashMap<String, Object>();
            expected.put("smtp_host", "smtp.example.com");
            expected.put("smtp_auth_enabled", "true");
            expected.put("smtp_starttls_enabled", "true");
            expected.put("jdk8_builtin_jaf_available", true);
            expected.put("external_javax_mail_not_bundled", false);

            Map<String, Object> actual = new LinkedHashMap<String, Object>();
            actual.put("smtp_host", props.getProperty("mail.smtp.host"));
            actual.put("smtp_auth_enabled", props.getProperty("mail.smtp.auth"));
            actual.put("smtp_starttls_enabled", props.getProperty("mail.smtp.starttls.enable"));
            actual.put("jdk8_builtin_jaf_available", hasJafInJdk8);
            actual.put("external_javax_mail_not_bundled", hasExternalJavaxMail);

            cases.add(makeCase(
                "smtp_properties_and_jdk8_jaf_check",
                "验证 SMTP Properties 认证与 STARTTLS 参数配置,以及 OpenJDK 8 内置 javax.activation 可用性与外部 javax.mail 依赖边界",
                expected,
                actual
            ));
        }

        Map<String, Object> root = new LinkedHashMap<String, Object>();
        root.put("version", "OpenJDK " + System.getProperty("java.version"));
        root.put("cases", cases);
        System.out.println(toJson(root));
    }
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。

入口文件:projects/java-sending-email-lab/ExploreSendingEmail.java

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreSendingEmail.java,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Java

课程关联工程包(登记关联57章) · 含当前章节或实例 · mbskycom202612a1104.zip

下载课程关联工程包:Java

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1150.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习