프로그래밍/자바

자바에서 구글메일로 메일보내기

RBWSN 2015. 6. 5. 22:28
728x90


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
package dao.service.mail;
 
import java.util.Properties;
 
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class MainSender {
 
    public static void main(String[] args) {
        //프로퍼티 생성
         Properties properties = new Properties();
        //프로퍼티에 smtp 서버 키와 값 입력
        properties.put("mail.smtp.starttls.enable""true");     
        properties.put("mail.smtp.host""smtp.gmail.com");      
        properties.put("mail.smtp.auth","true");                 
        properties.put("mail.smtp.port""587");                
        
        //보낼 아이디 인증 (구글메일)
        Authenticator authenticator = new Authenticator() { 
            protected PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication("googleid@gmail.com""googlepasswod");
            }
        };
        
        //서버와 보낼 아이디 인증
        Session session = Session.getDefaultInstance(properties,authenticator);
        
        // 메세지에 주입
        MimeMessage message = new MimeMessage(session); 
        try {
            //수신자
            message.addRecipient(Message.RecipientType.TO, new InternetAddress("받는사람메일"));
            
            //제목
            message.setSubject("제목 입력");
            
            //내용
            message.setText("본문 내용");
            
            // 메일발송
            Transport.send(message); 
            System.out.println("완료");
        } catch (Exception e) {
            e.getStackTrace();
        }   
    }
 
}
 
cs


메인문안에 정의를해놓았다.

그냥 복붙만 하고 아이디와 비번 받는사람메일만 적어놓으면 된다.

만약 파일을 보내고싶으면 MimeMessge의 메서드들을 살펴보면된다.





728x90