2013년 9월 2일 월요일

자바로 만든 메일발송 프로그램 SMTP Application

자바로 만든 메일발송 프로그램 SMTP Application

SMTP(Simple Mail Transfer Protocol)는 단순한 메일 전송 프로토콜로서
보통 인터넷 서비스 업체에서 SMTP 서버를 메일 송신 서버로 POP(Post Office Protocol) 서버를 메일 수신 서버로 두며 하나의 호스트에 두 서비스를 두기도 하지만 보통 두 서버를 나눕니다.  SMTP는 안정적인 메일의 전송을 위해 TCP 세션을 이용하는것은 다아시죠...

다음의 예를 보도록 하자구요...

import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class SendMailApplication  extends  JFrame{
private JTextField from;   
private JTextField to;   
private JTextField subject;   
private JTextArea message;   
private JButton sendButton, exitButton;
                private  Socket smtp;                       //SMTP서버에 접속하기 위한 소켓
private  BufferedReader input;          //서버의 응답을 저장하기 위한것
private  PrintStream output;              // 서버와의 통신을 위한 PrintStream
private  String serverReply;               // 서버응답
private String smtpServer = "211.209.7.147";  //SMTP서버 주소
private int  port = 25;

     // --------------------------------------------------------------------------
     // 1. 생성자에서 기본적인 윈도우 화면을 그린다.
// --------------------------------------------------------------------------
public SendMailApplication() {
Container cp = getContentPane();
cp.setLayout(new GridLayout(5,1));

from = new JTextField("",20);
from.setCaretColor(Color.blue);

                                to = new JTextField("",20);
to.setCaretColor(Color.blue);

subject = new JTextField("",20);
subject.setCaretColor(Color.blue);

message = new JTextArea(20,20);
message.setCaretColor(Color.blue);

sendButton = new JButton("전송하기...");
sendButton.setToolTipText("여길 누르시면 메일이 발송 됩니다...");

exitButton = new JButton("종료");
exitButton.setToolTipText("프로그램 종료...");


                                cp.add(new JLabel("From : "));  cp.add(from);
cp.add(new JLabel("To : "));  cp.add(to);
cp.add(new JLabel("subject : "));  cp.add(subject);
cp.add(new JLabel("message : "));  cp.add(message);
cp.add(sendButton);
      cp.add(exitButton);

//메일발송 버튼에 이벤트 검
sendButton.addActionListener( new ActionListener() 
{
public void actionPerformed(ActionEvent ae)  {
send();
}
}
);
    
                                //종료버튼에 이벤트 검
exitButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae)  {
System.exit(0);
}
}
);
setSize(300, 150); setVisible(true);
}

// --------------------------------------------------------------------------
     // 1. main 메소드(프로그램 시작 부분)
// --------------------------------------------------------------------------
public static void main(String[] args) {
new SendMailApplication();
}


                // --------------------------------------------------------------------------
// 1. "메일발송" 버튼을 클릭 했을때 호출되는 메소드
  // 2. 메일을 보내기 위한 모든 메소드를 Call 
// --------------------------------------------------------------------------
   public  void send() {
     try  {
     connect();
  hail(from.getText(), to.getText());
  sendMessage(from.getText(), to.getText(), subject.getText(), message.getText());
  logout();
  new MyDialog(this,"전송완료", "메일 전송이 완료 되었습니다...");
     }
    catch (SMTPException se)     {
new MyDialog(this,"전송오류(send)", se.getMessage());
     }


                                     catch (Exception e)      {
new MyDialog(this,"전송오류(send)", e.toString());
     }   
   }    
   // --------------------------------------------------------------------------
   //  메일서버에 접속을 하는 메소드
   //  1. 접속후 서버로 부터의 응답을 파악(200인 경우 서비스 준비OK)
   // --------------------------------------------------------------------------
   public void connect() throws SMTPException {
  try   {
  smtp = new Socket(smtpServer, port);
  input = new BufferedReader(new InputStreamReader(smtp.getInputStream()));
  //접속된 서버에 출력을 보내기위한 스트림을 생성한다.  
  output = new PrintStream(smtp.getOutputStream());  
  serverReply = input.readLine();


                                                  if (serverReply.charAt(0) == '2' || serverReply.charAt(0) == '3') {
  }
  else {
  throw new SMTPException("(connect)Error connecting to SMTP server " + smtpServer + "on port " + port);
  }
  }
  catch (Exception e)   {
  System.out.println("(connect)"+e.toString());
  throw new SMTPException("(connect)"+e.getMessage());
  }   
   } 

   // --------------------------------------------------------------------------
   // 메일 보내는이, 받는이등을 메일서버에게 알림...메일발송의 시작
   // --------------------------------------------------------------------------

                     public void hail(String from,  String to) throws SMTPException {
  if (submitCommand("HELO " + smtpServer))
  throw new SMTPException("(hail)Error occurred during HELO command.");
  if (submitCommand("MAIL FROM: " + from))
  throw new SMTPException("(hail)Error during MAIL command.");
  if (submitCommand("RCPT TO: " + to)) 
  throw new SMTPException("(hail)Error during RCPT command.");
   } 

   // --------------------------------------------------------------------------
   //  1. 실제 메일을 전송
   //   2. DATA명령은 SMTP 서버에게 메일을 보낸다고 알리는 기능
   // --------------------------------------------------------------------------


                    public void sendMessage(String from,  String to,  String subject,  String message) throws
   SMTPException {     
Date ldate_today = new Date(System.currentTimeMillis());
SimpleDateFormat lgmt_date = new 
SimpleDateFormat("d MMM yyyy HH:mm:ss 'GMT'");
lgmt_date.setTimeZone(TimeZone.getTimeZone("GMT"));
lgmt_date.format(ldate_today);
try  {  
   if (submitCommand("DATA"))  
   throw new SMTPException("Error during DATA command.");
   String header = "From: " + from + "\r\n";
   header += "To: " + to + "\r\n";
   header += "Subject: " + han(subject) + "\r\n";
   header += "Date: " + lgmt_date + "\r\n\r\n";


                                   if (submitCommand(header + han(message) + "\r\n."))
  throw new SMTPException("Error during mail transmission.");      
}
catch (Exception e)   {   
System.out.println("(sendMessage)"+e.toString());
throw new SMTPException("(sendMessage)"+e.getMessage());
}
   }

   // --------------------------------------------------------------------------
   //  1. 서버에 명령을 보낸후 응답을 받음
   //   2. Boolean값을 return, true인 경우 에러
   // --------------------------------------------------------------------------


                    private boolean submitCommand(String command) throws SMTPException {
  try {
  output.print(command + "\r\n");
  serverReply = input.readLine();
  if (serverReply.charAt(0) == '4' || serverReply.charAt(0) == '5') //전송실패등..
  return true;
  else          return false;
  }
  catch(Exception e) {  
  System.out.println("(submitCommand)"+e.toString());
  throw new SMTPException("(submitCommand)"+e.getMessage());    
  }
  }


                  // --------------------------------------------------------------------------
   //  1. 서버로 부터 접속을 끊음
   // --------------------------------------------------------------------------
   public void logout() throws SMTPException {          
try {
  if (submitCommand("Quit"))
  throw new SMTPException("(logout)Error during QUIT command");
  input.close();   output.flush();   output.close();   smtp.close();
  }
catch(Exception e) {     
  System.out.println("(logout)"+e.toString());
  throw new SMTPException(e.getMessage());
  }
   }


                   // -----------------------------------------------------------------------------
   //
   // 1. 한글 변환 함수 
   //
   // -----------------------------------------------------------------------------
   public static String han(String Unicodestr) throws UnsupportedEncodingException {      
  if( Unicodestr == null)   return null;   
  return new String(Unicodestr.getBytes("8859_1"),"KSC5601");   
   }   
}




댓글 없음:

댓글 쓰기