구글 이메일 전송, Java 코드 예제

silvereun ㅣ 2024. 11. 19. 01:14

구글 메일 전송을 위한 Java 코드 예제


  • Java를 사용하여 구글 SMTP 서버를 통해 이메일을 자동으로 전송하는 방법 소개
  • 이메일 전송은 서버 모니터링, 시스템 알림, 리포트 발송 등 사용될 수 있음


SMTP 인증 설정 (SMTPAuthenticator)


public class SMTPAuthenticator extends Authenticator {
    protected PasswordAuthentication getPasswordAuthentication() {
        String username = "구글 계정"; 
        String password = "구글 앱 비밀번호";   // 2단계 인증 후 생성
        return new PasswordAuthentication(username, password);
    }
}

  • 구글 메일 서버에 로그인하기 위한 사용자 인증 정보를 제공한다.
  • 이메일 전송을 위해서는 2단계 인증을 설정하고, 생성된 앱 비밀번호를 사용해야 한다.
  • 구글 SMTP 서버를 사용할 때, 앱 비밀번호를 직접 코드에 입력하는 것은 보안상 위험하므로 환경 변수나 별도의 보안 설정 파일에서 관리하는 것이 좋음


메일 발송 메서드 (sendMail)


public void sendMail(Map<String, Object> params //메일 내용 작성 시 필요한 파라미터 객체
                        , String to //수신자의 이메일 주소
                    ) throws Exception {
    try {
        String title = "메일 제목";
        StringBuilder sb = new StringBuilder();
        sb.append("<html lang=\"ko\" style=\"padding:0; margin:0;\">");
        sb.append("<head><meta charset=\"utf-8\"><title></title></head>");
        sb.append("<body style=\"padding:0; margin:0;\">");
        sb.append("<div style=\"margin: 30px auto; max-width: 600px; font-family: Malgun Gothic, sans-serif;\">");
        sb.append("<h1>메일 제목</h1>");
        sb.append("<p>이메일 본문 내용</p>");
        sb.append("</div></body></html>");

        //메일 옵션 설정
        String mail_EncodingType = "euc-kr";
        Properties prop = System.getProperties();
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.port", "465"); // SSL 포트
        prop.put("mail.mime.charset", mail_EncodingType);
        prop.put("mail.mime.encodefilename", "true");
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.protocols", "TLSv1.2");

        //메일 세션 생성
        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(prop, auth);


        //create a messeage
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("발신자 이메일"));
        InternetAddress[] address = { new InternetAddress(to) };
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject(title);
        message.setSentDate(new Date());


        // 메일 콘텐츠 설정
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(sb.toString(), "text/html; charset=utf-8");

        // 이미지 첨부
        MimeBodyPart imagePart = new MimeBodyPart();
        DataSource fds = new FileDataSource(staticImagePath+File.separator+"logo.png");
        imagePart.setDataHandler(new DataHandler(fds));
        imagePart.setHeader("Content-ID", "<logo.png>");  // CID 설정

         Multipart mp = new MimeMultipart();
         mp.addBodyPart(mbp1);
         mp.addBodyPart(imagePart);

         message.setContent(mp);

         // 메일 발송
         Transport.send(message);
         sb.setLength(0);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

  • 메일 서버 설정과 인증 정보를 포함한 SMTPAuthenticator로 메일 세션을 생성한다.
  • StringBuilder로 이메일 본문을 HTML 형식으로 작성하고, 제목에 따라 내용을 다르게 설정한다.
  • MimeMessage 객체를 생성하여 메일 메시지의 송신자, 수신자, 제목, 전송일을 설정한다.
  • 본문을 HTML 형식으로 설정하고, MimeBodyPart를 사용해 이메일 본문을 설정한다.
  • staticImagePath에 저장된 로고 이미지를 첨부파일로 추가한다. 이미지는 Content-ID를 통해 HTML 본문에서 참조할 수 있도록 설정된다.
  • 메일 본문과 이미지를 MimeBodyPart로 구성하고, 이를 Multipart로 묶어 MimeMessage에 설정한다.
  • Transport.send() 메서드를 호출하여 이메일을 전송