JavaMail :: 인증을 요하는 메일 SMTP에 접속하는 방법

2007/08/22 16:33

서비 JAVA , , ,

얼마전 인증을 해야하는 SMTP에 연결해야 했는데 그 방법 때문에 매우 고민했었습니다.
Mail API에서 Authenticator는 제공을 하면서 ID와 PW를 설정하는 부분이 없어서
참 난감했었습니다. 영어 실력이 짧아서 관련 Document를 읽어보다가 못찾고
다만 API에 있는 Session 클래스의
getInstance(Properties prop, Authenticator auth) 메소드가 마음에 걸려
혹시나 하는 마음으로 만들어 봤었는데 잘 되더군요.
sendmail 과 qmail 및 윈도기반 smtp server 몇 곳을 테스트 해봤는데 잘 되었습니다.

클래스 전체 소스는 다음과 같습니다.

/*
* MyAuthenticator.java
* 2002.05.27.
* Hyunho Kim(falllove@ducc.or.kr)
*
* Copyrightⓒ 2002 FancyArts Corps. All rights reserved.
*/

/**
* SMTP Authenticator
*/
public final class MyAuthenticator extends javax.mail.Authenticator {

    private String id;
    private String pw;

    public MyAuthenticator(String id, String pw) {
        this.id = id;
        this.pw = pw;
    }

    protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
        return new javax.mail.PasswordAuthentication(id, pw);
    }

}

사용하실 때는 session을 얻기 전에 프로퍼티에 mail.smtp.auth 항목을 추가하시고
MyAuthenticator의 인스턴스를 하나 만드셔서 인자로 넘기시면 됩니다.

Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp_host_name");
prop.put("mail.smtp.auth", "true");

MyAuthenticator auth = new MyAuthenticator("smpt_id", "smtp_pw");

// 새로운 메일 세션
Session mailSession = Session.getInstance(props, auth);
// or Session mailSession = Session.getDefaultInstance(props, auth);

정말 간단하죠^^;; 정말 암 것도 없는데 전에 이것을 하기 위해서 그 많은 글을 뒤적일
때는 못찾겠더라구요. 전 만들긴 했었지만 실제 서비스는 sendmail에서
localhost relay를 허용해서 사용하고 인증없이 발송하고 있습니다.
2007/08/22 16:33 2007/08/22 16:33
Trackback Address:이 글에는 트랙백을 보낼 수 없습니다