메일을 보내기 위해서는 메일 서버가 필요하다. 하지만 우리는 메일 서버를 직접 두지 않고 빌려서 사용할 것이다.
우리는 cafe24의 서비스를 이용할 것이다. 이용할 수 있는 서비스가 알고 싶다면 아래 링크로 들어가면 설명이 있다.
https://hosting.cafe24.com/?controller=new_product_page&page=webmail
카페24 호스팅 | 온라인 비즈니스의 시작
웹메일/아웃룩 동시 제공 웹메일과 아웃룩(POP3, SMTP)을 동시에 제공하여 언제 어디서나 편리하게 메일을 이용할 수 있습니다.
hosting.cafe24.com
메일서버를 알려줘야 한다.
인증받은 아이디와 비밀번호 필요
메일 제목, 주소, 내용, 참조, 숨은 참조 등이 필요한데 자바에서 클래스로 제공한다. 하지만 스탠다드와 엔터프라이즈에는 없어서 오라클에서 제공하는 외부 라이브러리를 사용할 것이다.
mail 폴더를 생성하여 mailForm.jsp를 만들자
mailForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>
<!-- 본문 시작 mailForm.jsp-->
<h3>* 메일 보내기 *</h3>
<form method="post" action="mailProc.jsp">
<table class="table">
<tr>
<th>받는사람</th>
<td><input type="email" name="to"></td>
</tr>
<tr>
<th>보내는사람</th>
<td><input type="email" name="from"></td>
</tr>
<tr>
<th>제목</th>
<td><input type="text" name="subject"></td>
</tr>
<tr>
<th>내용</th>
<td><textarea rows="5" cols="30" name="content"></textarea></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="메일보내기" class="btn btn-primary">
<input type="reset" value="취소" class="btn btn-primary">
</td>
</tr>
</table>
</form>
<!-- 본문 끝 -->
<%@ include file="../footer.jsp"%>
JavaMail 라이브러리 다운로드
https://www.oracle.com/java/technologies/java-archive-downloads-java-plat-downloads.html
Java Archive Downloads - Java Platform Technologies
We’re sorry. We could not find a match for your search. We suggest you try the following to help find what you’re looking for: Check the spelling of your keyword search. Use synonyms for the keyword you typed, for example, try "application" instead of
www.oracle.com
https://www.oracle.com/java/technologies/java-archive-eepla-downloads.html
Java Archive Downloads - Java EE Platform
We’re sorry. We could not find a match for your search. We suggest you try the following to help find what you’re looking for: Check the spelling of your keyword search. Use synonyms for the keyword you typed, for example, try "application" instead of
www.oracle.com
activation.jar와 mail.jar를 lib에 넣자
압축을 푼 javamail1_4_7 폴더에 가면 docs 폴더가 있고 거기서 javadocs폴더에 가면 index라는 html 파일이 있다. 여기로 가면 클래스에 대한 설명이 있다.
mailProc.jsp
<%@page import="java.util.Properties"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>
<!-- 본문 시작 mailProc.jsp-->
<h3>* 메일 보내기 결과 *</h3>
<%
try {
//1)사용하고자 하는 메일 서버에서 인증받은 계정과 비밀번호 등록하기
//->MyAuthenticator 클래스 생성
//2)메일서버(POP3/SMTP) 지정하기
String mailServer = "mw-002.cafe24.com"; //cafe24 메일서버
} catch(Exception e) {
out.println("<p>메일 전송 실패!!" + e + "</p>");
out.println("<p><a href='javascript:history.back();'>[다시시도]</a></p>");
}//end
%>
<!-- 본문 끝 -->
<%@ include file="../footer.jsp"%>
net.utility패키지에 MyAuthenticator 클래스를 생성한다.
MyAuthenticator.java
상속은 javax.mail 패키지의 Authenticator 클래스이다.
package net.utility;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MyAuthenticator extends Authenticator{
//사용하고자 하는 메일서버(POP3, SMTP)에서 인증받은 계정 + 비번 등록
private PasswordAuthentication pa;
public MyAuthenticator() { //기본생성자
pa = new PasswordAuthentication("계정", "비밀번호"); //각자의 계정과 비밀번호 입력
}//end
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return pa;
}
}//class end
mailProc.jsp
<%@page import="javax.mail.Session"%>
<%@page import="net.utility.MyAuthenticator"%>
<%@page import="javax.mail.Authenticator"%>
<%@page import="java.util.Properties"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>
<!-- 본문 시작 mailProc.jsp-->
<h3>* 메일 보내기 결과 *</h3>
<%
try {
//1)사용하고자 하는 메일 서버에서 인증받은 계정과 비밀번호 등록하기
//->MyAuthenticator 클래스 생성
//2)메일서버(POP3/SMTP) 지정하기
String mailServer = "mw-002.cafe24.com"; //cafe24 메일서버
Properties props = new Properties();
props.put("mail.smtp.host", mailServer);
props.put("mail.smtp.auth", true);
//3)메일서버에서 인증받은 계정 + 비번
Authenticator myAuth = new MyAuthenticator(); //다형성
//4) 2)와 3)이 유효한지 검증
Session sess = Session.getInstance(props, myAuth);
out.print("메일 서버 인증 성공!!");
} catch(Exception e) {
out.println("<p>메일 전송 실패!!" + e + "</p>");
out.println("<p><a href='javascript:history.back();'>[다시시도]</a></p>");
}//end
%>
<!-- 본문 끝 -->
<%@ include file="../footer.jsp"%>
mailProc.jsp을 실행해서 인증 테스트를 해보자
mailProc.jsp
<%@page import="java.util.Date"%>
<%@page import="javax.mail.Transport"%>
<%@page import="javax.mail.internet.MimeMessage"%>
<%@page import="javax.mail.Message"%>
<%@page import="javax.mail.internet.InternetAddress"%>
<%@page import="net.utility.Utility"%>
<%@page import="javax.mail.Session"%>
<%@page import="net.utility.MyAuthenticator"%>
<%@page import="javax.mail.Authenticator"%>
<%@page import="java.util.Properties"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>
<!-- 본문 시작 mailProc.jsp-->
<h3>* 메일 보내기 결과 *</h3>
<%
try {
//1) 사용하고자 하는 메일 서버에서 인증받은 계정과 비밀번호 등록하기
//->MyAuthenticator 클래스 생성
//2) 메일서버(POP3/SMTP) 지정하기
String mailServer = "mw-002.cafe24.com"; //cafe24 메일서버
Properties props = new Properties();
props.put("mail.smtp.host", mailServer);
props.put("mail.smtp.auth", true);
//3) 메일서버에서 인증받은 계정 + 비번
Authenticator myAuth = new MyAuthenticator(); //다형성
//4) 2)와 3)이 유효한지 검증
Session sess = Session.getInstance(props, myAuth);
//out.print("메일 서버 인증 성공!!");
//5) 메일 보내기
request.setCharacterEncoding("UTF-8");
String to = request.getParameter("to").trim();
String from = request.getParameter("from").trim();
String subject = request.getParameter("subject").trim();
String content = request.getParameter("content").trim();
//엔터 및 특수문자 변경
content = Utility.convertChar(content);
content += "<hr>";
content += "<table border='1'>";
content += "<tr>";
content += " <th>상품명</th>";
content += " <th>상품가격</th>";
content += "</tr>";
content += "<tr>";
content += " <td>운동화</td>";
content += " <td><span style='color:red; font-weight: bold;'>15,000원</span></td>";
content += "</tr>";
content += "</table>";
//받는 사람 이메일 주소
InternetAddress[] address = {new InternetAddress(to)};
/*
수신인이 여러명인 경우
InternetAddress[] address = {new InternetAddress(to1),
new InternetAddress(to2),
new InternetAddress(to3), ~~~};
*/
//메일 관련 정보 작성
Message msg = new MimeMessage(sess);
//받는 사람
msg.setRecipients(Message.RecipientType.TO, address);
//참조 Message.RecipientType.CC
//숨은참조 Message.RecipientType.BCC
//보내는 사람
msg.setFrom(new InternetAddress(from));
//메일 제목
msg.setSubject(subject);
//메일 내용
msg.setContent(content, "text/html; charset=UTF-8");
//메일 보낸 날짜
msg.setSentDate(new Date());
//메일 전송
Transport.send(msg);
out.print(to+"님에게 메일이 발송되었습니다");
} catch(Exception e) {
out.println("<p>메일 전송 실패!!" + e + "</p>");
out.println("<p><a href='javascript:history.back();'>[다시시도]</a></p>");
}//end
%>
<!-- 본문 끝 -->
<%@ include file="../footer.jsp"%>
메일을 한번 보내보자
위와 같이 메일이 제대로 왔다.
이번에는 이미지를 출력해보자
<%@page import="java.util.Date"%>
<%@page import="javax.mail.Transport"%>
<%@page import="javax.mail.internet.MimeMessage"%>
<%@page import="javax.mail.Message"%>
<%@page import="javax.mail.internet.InternetAddress"%>
<%@page import="net.utility.Utility"%>
<%@page import="javax.mail.Session"%>
<%@page import="net.utility.MyAuthenticator"%>
<%@page import="javax.mail.Authenticator"%>
<%@page import="java.util.Properties"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>
<!-- 본문 시작 mailProc.jsp-->
<h3>* 메일 보내기 결과 *</h3>
<%
try {
//1) 사용하고자 하는 메일 서버에서 인증받은 계정과 비밀번호 등록하기
//->MyAuthenticator 클래스 생성
//2) 메일서버(POP3/SMTP) 지정하기
String mailServer = "mw-002.cafe24.com"; //cafe24 메일서버
Properties props = new Properties();
props.put("mail.smtp.host", mailServer);
props.put("mail.smtp.auth", true);
//3) 메일서버에서 인증받은 계정 + 비번
Authenticator myAuth = new MyAuthenticator(); //다형성
//4) 2)와 3)이 유효한지 검증
Session sess = Session.getInstance(props, myAuth);
//out.print("메일 서버 인증 성공!!");
//5) 메일 보내기
request.setCharacterEncoding("UTF-8");
String to = request.getParameter("to").trim();
String from = request.getParameter("from").trim();
String subject = request.getParameter("subject").trim();
String content = request.getParameter("content").trim();
//엔터 및 특수문자 변경
content = Utility.convertChar(content);
content += "<hr>";
content += "<table border='1'>";
content += "<tr>";
content += " <th>상품명</th>";
content += " <th>상품가격</th>";
content += "</tr>";
content += "<tr>";
content += " <td>운동화</td>";
content += " <td><span style='color:red; font-weight: bold;'>15,000원</span></td>";
content += "</tr>";
content += "</table>";
//이미지 출력하기
content += "<hr>";
content += "<img src='http://localhost:9090/myweb/images/devil.png'>";
//받는 사람 이메일 주소
InternetAddress[] address = {new InternetAddress(to)};
/*
수신인이 여러명인 경우
InternetAddress[] address = {new InternetAddress(to1),
new InternetAddress(to2),
new InternetAddress(to3), ~~~};
*/
//메일 관련 정보 작성
Message msg = new MimeMessage(sess);
//받는 사람
msg.setRecipients(Message.RecipientType.TO, address);
//참조 Message.RecipientType.CC
//숨은참조 Message.RecipientType.BCC
//보내는 사람
msg.setFrom(new InternetAddress(from));
//메일 제목
msg.setSubject(subject);
//메일 내용
msg.setContent(content, "text/html; charset=UTF-8");
//메일 보낸 날짜
msg.setSentDate(new Date());
//메일 전송
Transport.send(msg);
out.print(to+"님에게 메일이 발송되었습니다");
} catch(Exception e) {
out.println("<p>메일 전송 실패!!" + e + "</p>");
out.println("<p><a href='javascript:history.back();'>[다시시도]</a></p>");
}//end
%>
<!-- 본문 끝 -->
<%@ include file="../footer.jsp"%>
'웹개발 교육 > jsp' 카테고리의 다른 글
[59일] jsp (34) - myweb 프로젝트(첨부 게시판 기초) (0) | 2022.10.20 |
---|---|
[58~9일] jsp (33) - myweb 프로젝트(아이디, 비밀번호 찾기) (0) | 2022.10.19 |
[57일] jsp (31) - myweb 프로젝트(회원가입 유효성 검사) (0) | 2022.10.18 |
[57일] jsp (30) - myweb 프로젝트(id 중복 확인) (0) | 2022.10.18 |
[57일] jsp (29) - myweb 프로젝트(로그인 시 id 저장) (0) | 2022.10.18 |