TopDev

Hàm gửi email google SMTP gmail bằng java

minhdev 📖 2 phút đọc

Dưới đây là phiên bản đã tối ưu và clean code của hàm SendEMailOTP:



Phiên bản clean code, dễ bảo trì, có timeout và log lỗi:#

` import javax.mail.; import javax.mail.internet.; import java.util.*;

public class MailUtil {

public static int sendEmailOTP(String to, String from, String pass, String title, String content) {
    final String SMTP_HOST_NAME = "smtp.gmail.com";
    final int SMTP_HOST_PORT = 587;
    final String MAIL_NAME = "Email Name";

    int result = 0;

    try {
        // 1. Cấu hình thuộc tính gửi mail
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.port", SMTP_HOST_PORT);
        props.put("mail.smtp.ssl.trust", SMTP_HOST_NAME);
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");

        // ✅ Cấu hình timeout
        props.put("mail.smtp.connectiontimeout", 10000); // 10s
        props.put("mail.smtp.timeout", 10000);           // 10s
        props.put("mail.smtp.writetimeout", 10000);      // 10s

        // 2. Tạo phiên gửi mail có xác thực
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, pass);
            }
        });

        // 3. Tạo message
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from, MAIL_NAME, "UTF-8"));

        // 4. Xử lý danh sách người nhận
        if (to == null || to.trim().isEmpty()) {
            System.err.println("Không có địa chỉ email người nhận.");
            return 0;
        }

        String[] emailToList = to.split(",");
        for (String email : emailToList) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.trim()));
        }

        // 5. Thiết lập tiêu đề và nội dung
        message.setSubject(title, "UTF-8");
        message.setContent(content, "text/html; charset=UTF-8");
        message.setSentDate(new Date());

        // 6. Gửi mail
        Transport.send(message);
        System.out.println("Gửi email thành công.");
        result = 1;

    } catch (AddressException e) {
        System.err.println("Lỗi địa chỉ email: " + e.getMessage());
        e.printStackTrace();
    } catch (MessagingException e) {
        System.err.println("Lỗi gửi email: " + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println("Lỗi không xác định: " + e.getMessage());
        e.printStackTrace();
    }

    return result;
}

} `



✅ Ưu điểm của phiên bản này:#

Điểm mạnh Mô tả
Sạch sẽ Code ngắn gọn, không dư thừa
Có timeout Hạn chế treo ứng dụng khi SMTP chậm
Có log lỗi rõ ràng Dễ debug nếu email không gửi được
Hỗ trợ tiếng Việt (UTF-8) Gửi tiêu đề + nội dung email Unicode
Có kiểm tra đầu vào Không gửi nếu không có địa chỉ to


🔁 Nếu bạn muốn bổ sung thêm:#

  • Gửi file đính kèm

  • Gửi email CC/BCC

  • Tích hợp template HTML chuyên nghiệp

Mình có thể mở rộng code theo yêu cầu.

Bạn có muốn gửi email kèm OTP dạng số ngẫu nhiên không? Mình cũng có thể gợi ý cách sinh và gửi OTP luôn.

Bài liên quan trong #Java

✓ Đã sao chép link