import javax.activation.DataHandler;
import javax.activation.FileDataSource;
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.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
public class ExploreSendingEmail {
static String esc(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 '\b': sb.append("\\b"); break;
case '\f': sb.append("\\f"); 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.toString();
}
static String caseJson(String name, String summary, String expected, String actual) {
boolean passed = expected.equals(actual);
return " {\"name\": \"" + esc(name) + "\", \"summary\": \"" + esc(summary)
+ "\", \"expected\": \"" + esc(expected) + "\", \"actual\": \"" + esc(actual)
+ "\", \"passed\": " + passed + "}";
}
static int readCode(BufferedReader in) throws Exception {
String line = in.readLine();
return Integer.parseInt(line.substring(0, 3));
}
public static void main(String[] args) throws Exception {
List<String> cases = new ArrayList<String>();
// Case 1: Real loopback mock SMTP handshake for plain-text RFC 5322 email
final AtomicReference<String> receivedData = new AtomicReference<String>("");
final List<String> rcptList = new ArrayList<String>();
final ServerSocket smtpServer = new ServerSocket(0, 5, InetAddress.getByName("127.0.0.1"));
Thread serverThread = new Thread(() -> {
try (Socket client = smtpServer.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.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") || line.startsWith("HELO")) {
out.write("250 localhost\r\n");
out.flush();
} else if (line.startsWith("MAIL FROM:")) {
out.write("250 OK\r\n");
out.flush();
} else if (line.startsWith("RCPT TO:")) {
rcptList.add(line.substring("RCPT TO:".length()).trim());
out.write("250 OK\r\n");
out.flush();
} else if (line.equals("DATA")) {
out.write("354 Start mail input\r\n");
out.flush();
StringBuilder body = new StringBuilder();
String dLine;
while ((dLine = in.readLine()) != null) {
if (".".equals(dLine)) {
break;
}
body.append(dLine).append("\n");
}
receivedData.set(body.toString());
out.write("250 Queued\r\n");
out.flush();
} else if (line.equals("QUIT")) {
out.write("221 Bye\r\n");
out.flush();
break;
}
}
} catch (Exception ignored) {
}
});
serverThread.start();
List<Integer> smtpCodes = new ArrayList<Integer>();
try (Socket sock = new Socket("127.0.0.1", smtpServer.getLocalPort());
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8))) {
smtpCodes.add(readCode(in));
out.write("HELO localhost\r\n"); out.flush(); smtpCodes.add(readCode(in));
out.write("MAIL FROM:<web@example.com>\r\n"); out.flush(); smtpCodes.add(readCode(in));
out.write("RCPT TO:<abcd@example.com>\r\n"); out.flush(); smtpCodes.add(readCode(in));
out.write("DATA\r\n"); out.flush(); smtpCodes.add(readCode(in));
out.write("From: web@example.com\r\n"
+ "To: abcd@example.com\r\n"
+ "Subject: This is the Subject Line!\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n\r\n"
+ "This is actual message\r\n.\r\n");
out.flush();
smtpCodes.add(readCode(in));
out.write("QUIT\r\n"); out.flush(); smtpCodes.add(readCode(in));
} finally {
serverThread.join(3000);
smtpServer.close();
}
String rcv = receivedData.get();
String act1 = "codes=" + smtpCodes.toString()
+ "|rcpts=" + rcptList.toString()
+ "|hasSubject=" + rcv.contains("Subject: This is the Subject Line!")
+ "|hasBody=" + rcv.contains("This is actual message");
String exp1 = "codes=[220, 250, 250, 250, 354, 250, 221]|rcpts=[<abcd@example.com>]|hasSubject=true|hasBody=true";
cases.add(caseJson("loopback_smtp_plain_text_send", "通过本地回环 ServerSocket 实测 SMTP 握手与纯文本 RFC 5322 投递", exp1, act1));
// Case 2: Multi-recipient TO / CC / BCC header vs envelope separation
List<String> toList = Arrays.asList("alice@example.com", "bob@example.com");
List<String> ccList = Arrays.asList("team@example.com");
List<String> bccList = Arrays.asList("audit@example.com");
List<String> envelopeRcpts = new ArrayList<String>();
envelopeRcpts.addAll(toList);
envelopeRcpts.addAll(ccList);
envelopeRcpts.addAll(bccList);
String visibleHeaders = "To: " + String.join(", ", toList) + "\r\nCc: " + String.join(", ", ccList);
String act2 = "envelopeCount=" + envelopeRcpts.size()
+ "|toInHeader=" + visibleHeaders.contains("bob@example.com")
+ "|ccInHeader=" + visibleHeaders.contains("team@example.com")
+ "|bccHiddenFromHeader=" + (!visibleHeaders.contains("audit@example.com"));
String exp2 = "envelopeCount=4|toInHeader=true|ccInHeader=true|bccHiddenFromHeader=true";
cases.add(caseJson("multi_recipient_rfc5322_headers", "验证多收件人 TO/CC/BCC 的信封与可见邮件头隔离规则", exp2, act2));
// Case 3: HTML MIME + multipart/mixed attachment + JDK 8 built-in javax.activation check
Path tmpFile = Files.createTempFile("servlet-mail-attach-", ".txt");
try {
byte[] attachPayload = "Attachment body line for Servlet mail.".getBytes(StandardCharsets.UTF_8);
Files.write(tmpFile, attachPayload);
FileDataSource fds = new FileDataSource(tmpFile.toFile());
DataHandler dh = new DataHandler(fds);
String b64 = Base64.getEncoder().encodeToString(attachPayload);
String boundary = "----MailBoundary8899";
String mime = "MIME-Version: 1.0\r\n"
+ "Content-Type: multipart/mixed; boundary=\"" + boundary + "\"\r\n\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Type: text/html; charset=UTF-8\r\n\r\n"
+ "<h1>This is actual message</h1>\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Type: text/plain; name=\"file.txt\"\r\n"
+ "Content-Transfer-Encoding: base64\r\n"
+ "Content-Disposition: attachment; filename=\"file.txt\"\r\n\r\n"
+ b64 + "\r\n"
+ "--" + boundary + "--\r\n";
byte[] decoded = Base64.getDecoder().decode(b64);
String act3 = "jafBuiltIn=" + (dh.getDataSource() instanceof FileDataSource)
+ "|hasHtmlPart=" + mime.contains("Content-Type: text/html; charset=UTF-8")
+ "|hasAttachmentDisp=" + mime.contains("Content-Disposition: attachment; filename=\"file.txt\"")
+ "|payloadExact=" + Arrays.equals(attachPayload, decoded);
String exp3 = "jafBuiltIn=true|hasHtmlPart=true|hasAttachmentDisp=true|payloadExact=true";
cases.add(caseJson("html_and_multipart_attachment_mime", "验证 HTML 正文、multipart/mixed Base64 附件封装与 JDK 8 内置 JAF DataHandler", exp3, act3));
} finally {
Files.deleteIfExists(tmpFile);
}
// Case 4: SMTP authentication Properties & RFC 4954 AUTH PLAIN encoding
Properties mailProps = new Properties();
mailProps.setProperty("mail.smtp.host", "localhost");
mailProps.setProperty("mail.smtp.auth", "true");
mailProps.setProperty("mail.user", "myuser");
mailProps.setProperty("mail.password", "mypwd");
String rawAuth = "\0" + mailProps.getProperty("mail.user") + "\0" + mailProps.getProperty("mail.password");
String encodedAuth = Base64.getEncoder().encodeToString(rawAuth.getBytes(StandardCharsets.UTF_8));
String decodedAuth = new String(Base64.getDecoder().decode(encodedAuth), StandardCharsets.UTF_8);
String[] authParts = decodedAuth.split("\0", -1);
boolean mailApiAbsent;
try {
Class.forName("javax.mail.Session");
mailApiAbsent = false;
} catch (ClassNotFoundException ex) {
mailApiAbsent = true;
}
String act4 = "host=" + mailProps.getProperty("mail.smtp.host")
+ "|auth=" + mailProps.getProperty("mail.smtp.auth")
+ "|user=" + authParts[1]
+ "|passLen=" + authParts[2].length()
+ "|javaMailExternal=" + mailApiAbsent;
String exp4 = "host=localhost|auth=true|user=myuser|passLen=5|javaMailExternal=true";
cases.add(caseJson("smtp_auth_properties_and_headers", "验证 mail.user/mail.password 属性、AUTH PLAIN 编码及外部 JavaMail 依赖边界", exp4, act4));
System.out.println("{");
System.out.println(" \"version\": \"Eclipse Adoptium OpenJDK " + esc(System.getProperty("java.version")) + "\",");
System.out.println(" \"cases\": [");
for (int i = 0; i < cases.size(); i++) {
System.out.println(cases.get(i) + (i + 1 < cases.size() ? "," : ""));
}
System.out.println(" ]");
System.out.println("}");
}
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
入口文件:projects/servlet-sending-email-lab/ExploreSendingEmail.java
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreSendingEmail.java,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1380.zip
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a1361.zip