Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

วิธีส่งอีเมลข้อความธรรมดา (Text) ด้วย JSP

ส่งอีเมล text แบบง่าย ใช้ MimeMessage.setText()

ข้อกำหนด

  • JavaMail API (mail.jar)
  • Java Activation Framework (activation.jar) - Java 8+ built-in
  • เพิ่มทั้ง 2 JAR ใน CLASSPATH / WEB-INF/lib

ตัวอย่าง SendEmail.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";
    
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", host);
    
    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("Test Email Subject");
        message.setText("This is a simple text message.");
        
        Transport.send(message);
        out.println("Email sent successfully!");
    } catch (MessagingException e) {
        e.printStackTrace();
        out.println("Error: " + e.getMessage());
    }
%>

การทดสอบ

  1. วางไฟล์ใน WEB-INF/lib mail.jar, activation.jar
  2. 2. Deploy บน Tomcat 3. เรียก https://localhost:8080/SendEmail.jsp

ผลลัพธ์

Send Email using JSP
Result: Sent message successfully....

SMTP Authentication (Production)

props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");  // TLS
props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props, new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("smtp_user", "smtp_password");
    }
});

แนวทางปฏิบัติ Production

  • อย่า hardcode credentials ใช้ JNDI / environment variables
  • ใช้ connection pooling (JavaMail ไม่มี built-in pool)
  • 3. Async sending (CompletableFuture / @Async) ไม่บล็อก request thread
  • Error handling และ retry logic
  • Logging แทน System.out
  • แยก email logic ออกจาก JSP (Service layer)