如何使用Java org.apache.commons.net.smtp.SMTPClient发送带附件的邮件
你使用的是Apache Commons Net组件的SMTPClient类,要支持附件发送需要构造MIME多部分格式的邮件内容,完整修改后的代码如下:
import org.apache.commons.net.smtp.SMTPClient; import org.apache.commons.net.smtp.SMTPReply; import java.io.File; import java.nio.file.Files; import java.util.Base64; // 类和方法定义根据你的实际代码调整 public void sendMailWithAttachment() throws Exception { SMTPClient client = new SMTPClient(); client.connect("mysmtp.domain.net"); int response = client.getReplyCode(); if (SMTPReply.isPositiveCompletion(response)) { // 修正原代码中发件人地址的语法错误(多余双引号) client.setSender("fromJohndoe@mydomain.com"); client.addRecipient("toJohndoe@mydomain.com"); // 定义MIME边界,用于分隔正文和附件 String boundary = "----=_MIME_Boundary_" + System.currentTimeMillis(); StringBuilder stringBuilder = new StringBuilder(); // 邮件头 stringBuilder.append("Subject: test\r\n"); stringBuilder.append("Content-Type: multipart/mixed; boundary=\"" + boundary + "\"\r\n\r\n"); // 正文部分 stringBuilder.append("--" + boundary + "\r\n"); stringBuilder.append("Content-Type: text/plain; charset=UTF-8\r\n\r\n"); stringBuilder.append("TEST msg\r\n\r\n"); // 附件部分 File attachmentFile = new File("/path/to/your/attachment.pdf"); // 替换为实际附件路径 String fileName = attachmentFile.getName(); stringBuilder.append("--" + boundary + "\r\n"); stringBuilder.append("Content-Type: application/octet-stream; name=\"" + fileName + "\"\r\n"); stringBuilder.append("Content-Disposition: attachment; filename=\"" + fileName + "\"\r\n"); stringBuilder.append("Content-Transfer-Encoding: base64\r\n\r\n"); // 附件内容Base64编码 byte[] fileContent = Files.readAllBytes(attachmentFile.toPath()); String encodedFile = Base64.getMimeEncoder().encodeToString(fileContent); stringBuilder.append(encodedFile).append("\r\n\r\n"); // MIME内容结束标记 stringBuilder.append("--" + boundary + "--\r\n"); client.sendShortMessageData(stringBuilder.toString()); boolean success = client.completePendingCommand(); if (success) { System.out.println("Message sent"); } } else { System.out.println("Error communicating with SMTP server"); } client.disconnect(); }
注意事项
- 代码中的
/path/to/your/attachment.pdf需要替换为你实际的附件本地路径 - 附件MIME类型可根据实际文件类型调整,比如png图片用
image/png、Excel文件用application/vnd.ms-excel,不确定类型的情况下用application/octet-stream即可兼容所有文件 - 示例使用JDK8内置的
java.util.Base64做编码,JDK8以下版本可替换为Apache Commons Codec的Base64工具类 - 如果附件体积超过10M,不建议使用
sendShortMessageData方法,改用client.getOutputStream()流写入避免内存溢出
内容的提问来源于stack exchange,提问作者devlover
相关产品推荐
相关产品推荐

