From 8775c3f46d516428902ad51bc878671ede834935 Mon Sep 17 00:00:00 2001 From: SangHyeok0908 Date: Fri, 15 Nov 2024 17:40:48 +0900 Subject: [PATCH 1/3] =?UTF-8?q?Refactor:=20=EC=A3=BC=EC=84=9D=20=EC=83=81?= =?UTF-8?q?=EC=84=B8=ED=99=94=20=EB=B0=8F=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/controller/SmtpController.java | 33 ++++++++---- SocketProgramming/src/model/SendMailDTO.java | 7 +++ .../src/util/commands/SmtpCommand.java | 53 ++++++++++--------- .../src/util/enums/MailPlatform.java | 4 ++ .../src/util/enums/SmtpStatusCode.java | 1 - SocketProgramming/src/view/SenderFrame.java | 29 ++++++++-- 6 files changed, 88 insertions(+), 39 deletions(-) diff --git a/SocketProgramming/src/controller/SmtpController.java b/SocketProgramming/src/controller/SmtpController.java index 1338a47..d578429 100644 --- a/SocketProgramming/src/controller/SmtpController.java +++ b/SocketProgramming/src/controller/SmtpController.java @@ -10,6 +10,12 @@ import java.io.*; import java.util.List; +/* + * SMTP 서버와 통신하는 클래스 + * @param senderAddress 발신자 이메일 주소 + * @param password 발신자 이메일 비밀번호 + * @param mailPlatform 은 senderAddress 도메인에 따라 SMTP 서버를 결정 + */ public class SmtpController { private final String senderAddress, password; @@ -27,16 +33,18 @@ public SmtpController(String senderAddress, String password) { } } + /* + * SMTP 서버와 인증하는 메소드 + * @return 인증 결과를 나타내는 SmtpStatusCode + * @throws IOException + */ public SmtpStatusCode authenticate() throws IOException { - List commands = SmtpCommand.createAuthCommands(this.senderAddress, this.password, this.mailPlatform); - SSLSocket sslSocket = createSSLSocket(); + List commands = SmtpCommand.createAuthCommands(this.senderAddress, this.password, this.mailPlatform); // 인증 명령어 생성 + SSLSocket sslSocket = createSSLSocket(); // SSL 소켓 생성 DataOutputStream outToServer = new DataOutputStream(sslSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(sslSocket.getInputStream())); String responseValue = inFromServer.readLine(); // 서버 응답 확인 - System.out.println("username: " + this.senderAddress); - System.out.println("password: " + password); - System.out.println("Response: " + responseValue); for (String command : commands) { @@ -45,7 +53,8 @@ public SmtpStatusCode authenticate() throws IOException { outToServer.flush(); // 명령 전송 후 플러시하여 보냄 System.out.println("SmtpCommand: " + command); - responseValue = inFromServer.readLine(); // 서버 응답 확인 + // 서버 응답 확인 + responseValue = inFromServer.readLine(); String statusCode = responseValue.split(" ")[0]; System.out.println("Response: " + responseValue); @@ -73,7 +82,7 @@ public SmtpStatusCode sendMail(SendMailDTO sendMailDTO) throws IOException, Inte SSLSocket sslSocket = createSSLSocket(); DataOutputStream outToServer = new DataOutputStream(sslSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(sslSocket.getInputStream())); - boolean isData = false; + boolean isData = false; // DATA 명령어인 경우 서버의 응답을 받을 필요 없어서 boolean 변수로 처리 String responseValue = inFromServer.readLine(); // 서버 응답 확인 System.out.println("Response: " + responseValue); @@ -85,15 +94,16 @@ public SmtpStatusCode sendMail(SendMailDTO sendMailDTO) throws IOException, Inte outToServer.flush(); // 명령 전송 후 플러시하여 보냄 System.out.println("SmtpCommand: " + commands.get(i)); - // DATA 명령어인 경우 데이터 전송 상태로 변경 + // DATA 명령어인 경우 서버의 응답을 받을 필요 없이 본문과 파일을 전송하기 때문에 isData 를 true 로 변경 if (i > 0 && commands.get(i - 1).contains("DATA\r\n")) { isData = true; } - // 데이터 전송이 끝난 경우 + // 본문과 파일 전송이 끝난 경우 다시 서버의 응답을 받기 위해 isData 를 false 로 변경 else if (commands.get(i).contains("\r\n.\r\n")) { isData = false; } + // DATA 명령어인 경우 서버의 응답을 받을 필요 없이 본문과 파일을 전송하기 때문에 continue if (isData) continue; @@ -122,9 +132,12 @@ else if (commands.get(i).contains("\r\n.\r\n")) { } + // 스트림과 소켓 닫기 inFromServer.close(); outToServer.close(); sslSocket.close(); + + // 메일 전송 완료 return SmtpStatusCode.SERVICE_CLOSING; } @@ -135,9 +148,11 @@ else if (commands.get(i).contains("\r\n.\r\n")) { */ private SSLSocket createSSLSocket() throws IOException { SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); + // 유효하지 않은 SMTP 서버인 경우 예외 처리 if (this.mailPlatform == null) { throw new IllegalArgumentException("Invalid email address"); } + // SMTP 서버에 맞는 SSL 소켓 생성 return (SSLSocket) sslSocketFactory.createSocket(this.mailPlatform.getSmtpServer(), 465); } } diff --git a/SocketProgramming/src/model/SendMailDTO.java b/SocketProgramming/src/model/SendMailDTO.java index 9197f92..9cbc17d 100644 --- a/SocketProgramming/src/model/SendMailDTO.java +++ b/SocketProgramming/src/model/SendMailDTO.java @@ -3,5 +3,12 @@ import java.io.File; import java.util.ArrayList; +/* + * 이메일 전송 정보를 담은 DTO + * @param recipient 수신자 이메일 주소 + * @param subject 이메일 제목 + * @param message 이메일 내용 + * @param attachedFiles 첨부 파일 목록 + */ public record SendMailDTO(String recipient, String subject, String message, ArrayList attachedFiles) { } diff --git a/SocketProgramming/src/util/commands/SmtpCommand.java b/SocketProgramming/src/util/commands/SmtpCommand.java index f9ab4c3..b0e82b0 100644 --- a/SocketProgramming/src/util/commands/SmtpCommand.java +++ b/SocketProgramming/src/util/commands/SmtpCommand.java @@ -33,41 +33,41 @@ public static ArrayList createAuthCommands(String senderAddress, String * createAuthCommands 메소드를 통해 SMTP 인증 명령어 생성 */ public static ArrayList createCommands(String senderAddress, String password, SendMailDTO sendMailDTO, MailPlatform mailPlatform) throws IOException { - String boundary = "----=_NextPart_" + System.currentTimeMillis(); + String boundary = "----=_NextPart_" + System.currentTimeMillis(); // multipart boundary ArrayList commands = new ArrayList<>(createAuthCommands(senderAddress, password, mailPlatform)); commands.remove(commands.size() - 1); // QUIT 명령어 제거 - commands.add("MAIL FROM:<" + senderAddress + ">\r\n"); - commands.add("RCPT TO:<" + sendMailDTO.recipient() + ">\r\n"); - commands.add("DATA\r\n"); + commands.add("MAIL FROM:<" + senderAddress + ">\r\n"); // 발신자 이메일 주소 설정 + commands.add("RCPT TO:<" + sendMailDTO.recipient() + ">\r\n"); // 수신자 이메일 주소 설정 + commands.add("DATA\r\n"); // 데이터 전송 명령어 // 이메일 헤더 설정 - commands.add("Subject: =?utf-8?B?" + encodeText(sendMailDTO.subject().getBytes(StandardCharsets.UTF_8)) + "?=\r\n"); - commands.add("To: " + sendMailDTO.recipient() + "\r\n"); - commands.add("From: " + senderAddress + "\r\n"); - commands.add("Content-Type: multipart/mixed; boundary=\"" + boundary + "\"\r\n"); - commands.add("\r\n"); + commands.add("Subject: =?utf-8?B?" + encodeText(sendMailDTO.subject().getBytes(StandardCharsets.UTF_8)) + "?=\r\n"); // 제목 + commands.add("To: " + sendMailDTO.recipient() + "\r\n"); // 수신자 이메일 주소 + commands.add("From: " + senderAddress + "\r\n"); // 발신자 이메일 주소 + commands.add("Content-Type: multipart/mixed; boundary=\"" + boundary + "\"\r\n"); // 본문 타입 설정 + commands.add("\r\n"); // 헤더와 본문 구분 // 본문 시작 - commands.add("--" + boundary + "\r\n"); - commands.add("Content-Type: text/plain; charset=\"UTF-8\"\r\n"); - commands.add("Content-Transfer-Encoding: base64\r\n"); - commands.add("\r\n" + encodeText(sendMailDTO.message().getBytes(StandardCharsets.UTF_8)) + "\r\n"); + commands.add("--" + boundary + "\r\n"); // boundary 시작 설정 + commands.add("Content-Type: text/plain; charset=\"UTF-8\"\r\n"); // 본문 타입 설정 + commands.add("Content-Transfer-Encoding: base64\r\n"); // 인코딩 설정 + commands.add("\r\n" + encodeText(sendMailDTO.message().getBytes(StandardCharsets.UTF_8)) + "\r\n"); // 본문 추가 // 첨부 파일 추가 for (File file : sendMailDTO.attachedFiles()) { - String encodedFileName = "=?utf-8?B?" + encodeText(file.getName().getBytes(StandardCharsets.UTF_8)) + "?="; - commands.add("--" + boundary + "\r\n"); - commands.add("Content-Type: " + getMimeType(file) + "; name=\"" + encodedFileName + "\"\r\n"); - commands.add("Content-Transfer-Encoding: base64\r\n"); - commands.add("Content-Disposition: attachment; filename=\"" + encodedFileName + "\"\r\n"); - commands.add("\r\n" + encodeFile(file) + "\r\n"); + String encodedFileName = "=?utf-8?B?" + encodeText(file.getName().getBytes(StandardCharsets.UTF_8)) + "?="; // 파일 이름 인코딩 + commands.add("--" + boundary + "\r\n"); // boundary 시작 설정 + commands.add("Content-Type: " + getMimeType(file) + "; name=\"" + encodedFileName + "\"\r\n"); // 파일 타입 설정 + commands.add("Content-Transfer-Encoding: base64\r\n"); // 인코딩 설정 + commands.add("Content-Disposition: attachment; filename=\"" + encodedFileName + "\"\r\n"); // 파일 이름 설정 + commands.add("\r\n" + encodeFile(file) + "\r\n"); // 파일 추가 } - // 종료 boundary 추가 - commands.add("--" + boundary + "--\r\n"); - commands.add("\r\n.\r\n"); - commands.add("QUIT\r\n"); + + commands.add("--" + boundary + "--\r\n"); // 종료 boundary 추가 + commands.add("\r\n.\r\n"); // 데이터 전송 종료 + commands.add("QUIT\r\n"); // QUIT 명령어 추가 return commands; } @@ -83,9 +83,14 @@ private static String getMimeType(File file) { return "application/octet-stream"; // 기본값은 바이너리 파일로 가정 } + /* + * 한글 깨지는 것을 방지하기 위해 Base64로 인코딩 + * 텍스트를 Base64로 인코딩 + * @param text 인코딩할 텍스트 + * @return Base64로 인코딩된 텍스트 + */ private static String encodeText(byte[] text) { return Base64.getEncoder().encodeToString(text); - } // 파일을 Base64로 인코딩 diff --git a/SocketProgramming/src/util/enums/MailPlatform.java b/SocketProgramming/src/util/enums/MailPlatform.java index 366b98a..c23401a 100644 --- a/SocketProgramming/src/util/enums/MailPlatform.java +++ b/SocketProgramming/src/util/enums/MailPlatform.java @@ -1,5 +1,9 @@ package util.enums; +/* + * 이메일 주소의 도메인에 따라 SMTP 서버를 결정 + * @param smtpServer SMTP 서버 주소 + */ public enum MailPlatform { NAVER("smtp.naver.com"), GMAIL("smtp.gmail.com"); diff --git a/SocketProgramming/src/util/enums/SmtpStatusCode.java b/SocketProgramming/src/util/enums/SmtpStatusCode.java index a772155..9a79d35 100644 --- a/SocketProgramming/src/util/enums/SmtpStatusCode.java +++ b/SocketProgramming/src/util/enums/SmtpStatusCode.java @@ -3,7 +3,6 @@ public enum SmtpStatusCode { SERVICE_CLOSING(221, "서버와의 연결이 종료되었습니다"), SERVICE_NOT_AVAILABLE(421, "SMTP 통신 중 time out 이 발생하였습니다.\n 다음에 이용해 주세요."), // timeout - SYNTAX_ERROR(500, "문법 오류입니다."), // 문법적 오류 RECIPIENT_NOT_FOUND(553, "발신자 주소가 올바르지 않습니다"), NOT_ACCEPTED(535, "사용자 인증에 실패하였습니다\n 아이디, 비밀번호, 보안 수준를 확인하여 주세요."),; diff --git a/SocketProgramming/src/view/SenderFrame.java b/SocketProgramming/src/view/SenderFrame.java index 9e1819b..ec2cd37 100644 --- a/SocketProgramming/src/view/SenderFrame.java +++ b/SocketProgramming/src/view/SenderFrame.java @@ -17,10 +17,10 @@ public class SenderFrame extends JFrame { - private final SmtpController senderController; + private final SmtpController senderController; // 메일 전송을 위한 controller private final JTextField receiverField, subjectField; // 받는사람, 제목 field private final JTextArea messageArea; // 본문 field - private final ArrayList attachedFiles; + private final ArrayList attachedFiles; // 첨부파일 목록 // 새로운 메일 쓰기 버튼을 눌렀을 때 호출 되는 생성자 public SenderFrame(String senderAddress, String password) { @@ -72,7 +72,6 @@ private void initFrame() { /* * form panel 을 생성하는 메소드 - * form panel 은 4개의 text field 로 구성되어 있음 */ private JPanel createFormPanel() { JPanel mainPanel = new JPanel(new GridLayout(2, 1)); @@ -93,7 +92,7 @@ private JPanel createFormPanel() { /* * button panel 을 생성하는 메소드 - * button panel 은 보내기 버튼과 취소 버튼으로 구성되어 있음 + * button panel 은 보내기 버튼과 취소 버튼, 10초 후 보내기 버튼으로 구성되어 있음 */ private JPanel createCheckButton() { JPanel buttonPanel = new JPanel(new GridLayout(1, 3)); @@ -138,6 +137,14 @@ private JPanel createTextArea(String text, JTextArea textField) { return textAreaPanel; } + /* + * file selection panel 을 생성하는 메소드 + * file selection panel 은 파일 선택 버튼과 파일 삭제 버튼, 파일 경로를 보여주는 text area 로 구성되어 있음 + * 파일 선택 버튼을 클릭하면 JFileChooser 를 이용하여 파일을 선택할 수 있음 + * 파일 삭제 버튼을 클릭하면 선택된 파일을 모두 삭제할 수 있음 + * 파일 경로는 text area 에 추가되어 보여짐 + * 선택된 파일은 attachedFiles 에 추가됨 + */ private JPanel createFileSelectionPanel() { JPanel result = new JPanel(new BorderLayout()); JButton fileSelectionButton = new JButton("파일 선택"); @@ -193,6 +200,11 @@ private void deleteFile(JTextArea filePathArea) { filePathArea.setText(""); } + /* + * 보내기 버튼을 클릭했을 때 호출되는 메소드 + * receiverField, subjectField, messageArea 에 입력된 값을 가져와서 + * controller 의 sendMail method 를 호출하여 메일을 전송함 + */ private void sendButtonOnClick(ActionEvent e) { ArrayList sendMailDTOs = createSendMailDTOs(); @@ -219,7 +231,8 @@ protected Void doInBackground() throws Exception { * 보내기 버튼을 클릭했을 때 호출되는 메소드 * receiverField, subjectField, messageArea 에 입력된 값을 가져와서 * controller 의 sendMail method 를 호출하여 메일을 전송함 - * 메일 전송 후 메일이 전송되었다는 팝업 메시지를 띄움 + * 메일 전송 실패 시 실패 팝업 메시지를 띄움 + * 메일 전송 성공 시 메일이 전송되었다는 팝업 메시지를 띄움 */ private void sendEmails(ArrayList sendMailDTOs) { SmtpStatusCode statusCode = null; @@ -252,6 +265,12 @@ private void sendEmails(ArrayList sendMailDTOs) { private ArrayList createSendMailDTOs() { ArrayList sendMailDTOs = new ArrayList<>(); + /* + * receiverField 에 입력된 이메일 주소를 , 를 기준으로 나누어 + * SendMailDTO 객체를 생성하여 sendMailDTOs 에 추가함 + * receiverField 에 입력된 이메일 주소는 , 를 기준으로 여러 개 입력할 수 있음 + * 이메일 주소는 <이메일 주소> 형태로 입력할 수 있음 + */ if (this.receiverField.getText().contains(",")) { String[] recipients = this.receiverField.getText().split(","); From f798e8070ed347099c98ae915b2fd97c5d368002 Mon Sep 17 00:00:00 2001 From: Seo SangHyeok <126949574+SangHyeok0908@users.noreply.github.com> Date: Mon, 30 Dec 2024 15:09:16 +0900 Subject: [PATCH 2/3] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 501bbd5..0402d8d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ # Socket-Programming -양쿤 러버 +SMTP Protocol 구현 From e0a327199cb0c067698160b998a58ef4a2750242 Mon Sep 17 00:00:00 2001 From: Seo SangHyeok <126949574+SangHyeok0908@users.noreply.github.com> Date: Mon, 30 Dec 2024 15:11:02 +0900 Subject: [PATCH 3/3] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0402d8d..4e00789 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ # Socket-Programming -SMTP Protocol 구현 +email 송수신 구현