본문 바로가기

Java & Html

Java - 메일 발송

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

필요 라이브러리

https://java.net/projects/javamail/pages/Home

자바 6 이후로는 javax.mail.jar만 필요하다. activation.jar가 jre에 기본으로 포함되었다.

네이버 메일 발송 테스트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package kr.co.goodcodes.servlet;
 
import java.util.Properties;
 
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class NaverMailTest {
    public static void main(String args[]) throws MessagingException{
        // 메일 관련 정보
        String host = "smtp.naver.com";
        final String username = "네이버아이디";
        final String password = "비밀번호";
        int port=465;
         
        // 메일 내용
        String recipient = "수신자";
        String subject = "네이버를 사용한 발송 테스트입니다.";
        String body = "내용 무";
         
        Properties props = System.getProperties();
         
         
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.trust", host);
          
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            String un=username;
            String pw=password;
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(un, pw);
            }
        });
        session.setDebug(true); //for debug
          
        Message mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress("발신자 정보"));
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        mimeMessage.setSubject(subject);
        mimeMessage.setText(body);
        Transport.send(mimeMessage);
    }
}

지메일 발송 테스트 – 기본모드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package kr.co.goodcodes.servlet;
 
import java.util.Properties;
 
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class GmailTest {
    public static void main(String args[]) throws MessagingException{
        // 메일 관련 정보
        String host = "smtp.gmail.com";
        String username = "지메일아이디@gmail.com";
        String password = "비밀번호";
         
        // 메일 내용
        String recipient = "수신자 메일주소";
        String subject = "지메일을 사용한 발송 테스트입니다.";
        String body = "내용 무";
         
        //properties 설정
        Properties props = new Properties();
        props.put("mail.smtps.auth", "true");
        // 메일 세션
        Session session = Session.getDefaultInstance(props);
        MimeMessage msg = new MimeMessage(session);
 
        // 메일 관련
        msg.setSubject(subject);
        msg.setText(body);
        msg.setFrom(new InternetAddress(username));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
 
        // 발송 처리
        Transport transport = session.getTransport("smtps");
        transport.connect(host, username, password);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();     
    }
}

지메일 발송 테스트 – TLS/SSL 사용시

두개의 차이점은 Properties에 담겨 있는 내용에 따라 달라진다. 두개의 차이점을 볼 수 있게 병기하였으나 실제 사용시에는 두개중 하나는 코멘트 처리해야만 한다.

msg.setFrom, msg.setReplyTo는 사실 잘 모르겠다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package kr.co.goodcodes.servlet;
 
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
 
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class GmailTLSorSSLTest {
    public static void main(String args[]) throws MessagingException, UnsupportedEncodingException{
        // 발신, 수신 정보
        final String fromEmail = "지메일 아이디@gmail.com";
        final String password = "비밀번호";
        final String toEmail = "수신자 메일";
         
        // 메일 내용
        String subject="메일 발송 테스트";
        String body="내용 무";
         
        Properties props = new Properties();
        // SSL 사용하는 경우
        props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
        props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
        props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
        props.put("mail.smtp.port", "465"); //SMTP Port
         
        // TLS 사용하는 경우
        props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
        props.put("mail.smtp.port", "587"); //TLS Port
        props.put("mail.smtp.auth", "true"); //enable authentication
        props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
         
        // 인증
        Authenticator auth = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, password);
            }
        };
         
        // 메일 세션
        Session session = Session.getInstance(props, auth);
         
        MimeMessage msg = new MimeMessage(session);
        //set message headers
        msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
        msg.addHeader("format", "flowed");
        msg.addHeader("Content-Transfer-Encoding", "8bit");
         
        msg.setFrom(new InternetAddress(fromEmail, "관리자"));
        msg.setReplyTo(InternetAddress.parse("no_reply@goodcodes.co.kr", false));
 
        msg.setSubject(subject, "UTF-8");
        msg.setText(body, "UTF-8");
        msg.setSentDate(new Date());
 
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
        Transport.send(msg); 
 
    }
}

네이버 메일 파일 첨부 테스트

네이버 메일 발송과 동일하나 msg.setText 대신에 Multipart를 생성하여 msg.setContent로 첨부하고 Multipart에 내용본문과 파일을 첨부하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package kr.co.goodcodes.servlet;
 
import java.util.Date;
import java.util.Properties;
 
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
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;
 
public class NaverMailTest {
    public static void main(String args[]) throws MessagingException{
        // 메일 관련 정보
        String host = "smtp.naver.com";
        final String username = "네이버아이디";
        final String password = "비밀번호";
        int port=465;
         
        // 메일 내용
        String recipient = "수신자";
        String subject = "네이버를 사용한 발송 테스트입니다.";
        String body = "내용 무";
         
        Properties props = System.getProperties();
         
         
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.trust", host);
          
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            String un=username;
            String pw=password;
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(un, pw);
            }
        });
        session.setDebug(true); //for debug
          
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("발신자 정보"));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
         
        // 파일 첨부시에는 BodyPart를 사용
        // msg.setText(body);
         
        // 파일첨부를 위한 Multipart
        Multipart multipart = new MimeMultipart();
         
        // BodyPart를 생성
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(body);
         
        // 1. Multipart에 BodyPart를 붙인다.
        multipart.addBodyPart(bodyPart);
         
        // 2. 파일을 첨부한다.
        String filename = "D:/restful_java_with_jax-rs.pdf";
        DataSource source = new FileDataSource(filename);
        bodyPart.setDataHandler(new DataHandler(source));
        bodyPart.setFileName(filename);
         
        // 이메일 메시지의 내용에 Multipart를 붙인다.
        msg.setContent(multipart);
        Transport.send(msg);
    }
}

네이버 이미지 첨부 테스트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package kr.co.goodcodes.servlet;
 
import java.util.Date;
import java.util.Properties;
 
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
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;
 
public class NaverMailTest {
    public static void main(String args[]) throws MessagingException{
        // 메일 관련 정보
        String host = "smtp.naver.com";
        final String username = "네이버아이디";
        final String password = "비밀번호";
        int port=465;
         
        // 메일 내용
        String recipient = "수신자";
        String subject = "네이버를 사용한 발송 테스트입니다.";
        String body = "내용 무";
         
        Properties props = System.getProperties();
         
         
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.trust", host);
          
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            String un=username;
            String pw=password;
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(un, pw);
            }
        });
        session.setDebug(true); //for debug
          
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("발신자 정보"));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
         
        // 파일 첨부시에는 BodyPart를 사용
        // msg.setText(body);
         
        // 파일첨부를 위한 Multipart
        Multipart multipart = new MimeMultipart();
         
        // BodyPart를 생성
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(body);
         
        // 1. Multipart에 BodyPart를 붙인다.
        multipart.addBodyPart(bodyPart);
         
        // 2. 이미지를 첨부한다.
        bodyPart = new MimeBodyPart();
        String filename = "D:/image.png";
        DataSource source = new FileDataSource(filename);
        bodyPart.setDataHandler(new DataHandler(source));
        bodyPart.setFileName(filename);
        //Trick is to add the content-id header here
        bodyPart.setHeader("Content-ID", "image_id");
        multipart.addBodyPart(bodyPart);
         
        //third part for displaying image in the email body
        bodyPart = new MimeBodyPart();
        bodyPart.setContent("<h1>Attached Image</h1>" + "<img src='cid:image_id'>", "text/html");
        multipart.addBodyPart(bodyPart);
         
        // 이메일 메시지의 내용에 Multipart를 붙인다.
        msg.setContent(multipart);
        Transport.send(msg);
    }
}

'Java & Html' 카테고리의 다른 글

Java7 특징 10가지  (0) 2015.06.29
DB컬럼을 빈값으로 만들기  (0) 2015.04.09
[spring] log4j 설정 및 사용법  (0) 2014.11.19
HttpServletRequest를 가져오는 방법  (1) 2014.03.24
java.util.Date 를 이용한 날짜 차이  (0) 2014.02.03