ใช้ JavaMail API และ Java Activation Framework (JAF) ส่งอีเมลพร้อม attachment
ตัวอย่าง SendEmailWithAttachment.jsp
<%@ page import="java.io.*,java.util.*,javax.mail.*" %>
<%@ page import="javax.mail.internet.*,javax.activation.*" %>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%
String to = "recipient@gmail.com";
String from = "sender@gmail.com";
String host = "localhost"; // SMTP server
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", host);
// ถ้าต้อง auth:
// props.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject with Attachment");
// Body part 1: text
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is message body");
// Multipart container
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Body part 2: attachment
messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Set content และส่ง
message.setContent(multipart);
Transport.send(message);
out.println("Sent successfully!");
} catch (MessagingException e) {
e.printStackTrace();
out.println("Error: " + e.getMessage());
}
%>
Authentication (ถ้า SMTP ต้องการ login)
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
ข้อกำหนด
- JavaMail API (mail.jar)
- Java Activation Framework (activation.jar) - Java 8+ รวมอยู่ใน JDK แล้ว
- SMTP server ที่เข้าถึงได้ (localhost หรือ remote)
โครงสร้าง MIME Message
MimeMessage
└── MimeMultipart (mixed)
├── MimeBodyPart (text/plain) -- body text
└── MimeBodyPart (attachment) -- file.txt
├── DataHandler
└── FileDataSource
หมายเหตุ: ใน Production ควรย้าย logic ไป Servlet/Service class แยกจาก JSP