Dev Note/Java2011. 8. 10. 21:16

java mail API를 이용하여 GMail의 SMTP를 이용하여 메일을 발송하는 것에 대해 아주 간략하게 알아본다.
메일을 발송하기 위해서는 Java Mail API와 GMail 계정이 필요하다. (GMail SMTP는 SSL로 계정 인증을 해야 사용이 가능하다.)

발송되는 메일의 텍스트는 HTML이며, UTF-8이다. Text나 다른 캐릭터셋을 원한다면 조금 수정하면 된다.
기능은 첨부파일이 있는 메일과 없는 메일만 구분하여 제공한다.

import java.io.File;

import java.util.Date;

import java.util.Properties;

 

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.Authenticator;

import javax.mail.Message;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

import javax.mail.internet.MimeUtility;

 

/**

 * <PRE>

 * SmtpMailer class

 * SMTP 이용하여 메일을 발송한다.

 * </PRE>

 *

 * @author ukzzang

 * @version v0.8, 2011. 8. 2.

 *

 *          <PRE>

 * - History

 *            2011. 8. 2., ukzzang, 최초작성.

 * </PRE>

 */

public class GmailSmtpSender {

 

    // gmail smtp default info

    public static final String DEFAULT_TRANSPORT_PROTOCOLC = "smtp";

    public static String DEFAULT_SMTP_SOCKET_FACTORY_CLASS 
           
"javax.net.ssl.SSLSocketFactory"
;

    public static String DEFAULT_SMTP_HOST = "smtp.gmail.com";

    public static int DEFAULT_SMTP_PORT = 465;

 

    private Properties props = null;

 

    /**

      * constructor

      */

    public GmailSmtpSender() {

        this(DEFAULT_SMTP_HOST, DEFAULT_SMTP_PORT,

                           DEFAULT_SMTP_SOCKET_FACTORY_CLASS);

    }

 

    /**

      * constructor

      *

      * @param host smtp host (domain or ip)

      * @param port smtp port

      * @param socketFactoryClassName smtp socket factory class name

      */

    public GmailSmtpSender(String host, int port, String socketFactoryClassName)
    {

        props = new Properties();

 

        // 기본 프로퍼티 설정

        props.put("mail.smtp.starttls.enable", "true");

        props.put("mail.smtp.auth", "true");

        props.put("mail.transport.protocol", DEFAULT_TRANSPORT_PROTOCOLC);

 

        // 지정 가능 프로퍼티 설정

        props.put("mail.smtp.host", host);

        props.setProperty("mail.smtp.socketFactory.class",

                           socketFactoryClassName);

        props.put("mail.smtp.port", String.valueOf(port)); 

    }

 

    /**

      * SMTP 이용하여 메이을 발송한다. (인증을 위해 Gmail 계정정보가 필요하며, 첨부파일 처리는 없다.)

      *

      * @param authId 인증 아이디

      * @param authPasswd 인증 패스워드

      * @param from 보내는 사람 메일 주소

      * @param fromName 보내는 사람 표현 이름

      * @param to 받는 메일 주소

      * @param cc 참조 메일 주소

      * @param bcc 숨은 참조 메일 주소

      * @param subject 메일 제목

      * @param content 메일 내용

      * @throws Exception

      */

    public void sendSmtpMail(String authId, String authPasswd, String from,
           
String fromName, String[] to, String[] cc, String[] bcc,

            String subject, String content) throws Exception {

        Message msg = createMessage(authId, authPasswd, from, fromName, 
                to, cc, 
bcc, null); // create message

 

        // subject & content

        msg.setSubject(subject);

        msg.setSentDate(new Date());

        msg.setContent(content, "text/html;charset=utf-8");

 

        Transport.send(msg); // send mail

    }

 

    /**

      * SMTP 이용하여 메이을 발송한다. (인증을 위해 Gmail 계정정보가 필요하며, 첨부파일 처리는 없다.)

      *

      * @param authId 인증 아이디

      * @param authPasswd 인증 패스워드

      * @param from 보내는 사람 메일 주소

      * @param fromName 보내는 사람 표현 이름

      * @param to 받는 메일 주소

      * @param cc 참조 메일 주소

      * @param bcc 숨은 참조 메일 주소

      * @param subject 메일 제목

      * @param content 메일 내용

      * @param attachFiles 첨부파일

      * @throws Exception

      */

    public void sendSmtpMail(String authId, String authPasswd, String from,

            String fromName, String[] to, String[] cc, String[] bcc,

            String subject, String content, File[] attachFiles)

            throws Exception {

        Message msg = createMessage(authId, authPasswd, from, fromName, to, cc,

                bcc, attachFiles); // create message

 

        // subject & content

        msg.setSubject(subject);

        msg.setSentDate(new Date());

 

        Object contentObj = msg.getContent();

        if (contentObj != null && contentObj instanceof Multipart) {

            MimeBodyPart contentPart = new MimeBodyPart();

            contentPart.setText(content);

            contentPart.setHeader("Content-Type", "text/html;charset=utf-8");

 

            Multipart mPart = (Multipart) contentObj;

            mPart.addBodyPart(contentPart);

        } else {

            msg.setContent(content, "text/html;charset=utf-8");

        }

 

        Transport.send(msg); // send mail

    }

 

    // 메시지를 생성한다.

    private Message createMessage(String authId, String authPasswd,

            String from, String fromName, String[] to, String[] cc,

            String[] bcc, File[] attachFiles) throws Exception {

        GmailSmtpAuthenticator auth = new GmailSmtpAuthenticator(authId,

                authPasswd); 

        Session mailSession = Session.getDefaultInstance(props, auth);

 

        // create message

        Message msg = new MimeMessage(mailSession);

 

        if (fromName != null) {

            msg.setFrom(new InternetAddress(from, MimeUtility.encodeText(

                    fromName, "UTF-8", "B")));

        } else {

            msg.setFrom(new InternetAddress(from));

        }

 

        // add to

        InternetAddress[] toAddr = null;

        if (to != null) {

            toAddr = new InternetAddress[to.length];

            for (int i = 0; i < to.length; i++) {

                toAddr[i] = new InternetAddress(to[i]);

            }

        } else {

            toAddr = new InternetAddress[1];

            toAddr[0] = new InternetAddress(authId);

        }

        msg.setRecipients(Message.RecipientType.TO, toAddr);

 

        // add cc (참조)

        if (cc != null) {

            InternetAddress[] ccAddr = new InternetAddress[cc.length];

            for (int i = 0; i < cc.length; i++) {

                ccAddr[i] = new InternetAddress(cc[i]);

            }

 

            msg.setRecipients(Message.RecipientType.CC, ccAddr);

        }

 

        // add bcc (숨은참조)

        if (bcc != null) {

            InternetAddress[] bccAddr = new InternetAddress[bcc.length];

            for (int i = 0; i < bcc.length; i++) {

                bccAddr[i] = new InternetAddress(bcc[i]);

            }

 

            msg.setRecipients(Message.RecipientType.BCC, bccAddr);

        }

 

        if (attachFiles != null) {

            // 파일 첨부

            Multipart multipart = new MimeMultipart();

 

            for (File attachFile : attachFiles) {

                if (attachFile != null && attachFile.exists()) {

                    MimeBodyPart mimeBodyPart = new MimeBodyPart();

 

                    mimeBodyPart.setDataHandler(new DataHandler(

                            new FileDataSource(attachFile)));

                    mimeBodyPart.setFileName(attachFile.getName());

 

                    multipart.addBodyPart(mimeBodyPart);

                }

            }

 

            msg.setContent(multipart);

        }

 

        return msg;

    }

 

    private static class GmailSmtpAuthenticator extends Authenticator {

 

        private String id = null;

        private String passwd = null;

 

        public GmailSmtpAuthenticator(String id, String passwd) {

            this.id = id;

            this.passwd = passwd;

        }

 

        @Override

        protected PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(id, passwd);

        }
    }
 

            

}

Java Mail의 mail.jar가 패스에 잡혀 있어야 한다.

Posted by as.wind.914