본문 바로가기
Front-end/JSP

JSP 이메일 보내기

by bloodFinger 2020. 1. 13.

2개의 jar 파일을 먼저 받고 라이브러리를 추가해준다!

activation.jar
0.05MB
mail.jar
0.50MB

 

SMTPAuthenticator.java

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class SMTPAuthenticator extends Authenticator{
	
	
	@Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("didwodn8822@gmail.com","****암호*****");
    }

}

 

 

SendMailAction.java

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.control.CommandProcess;

public class SendMailAction implements CommandProcess {

	@Override
	public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable {

		
		String email = request.getParameter("email");
		String subject = request.getParameter("subject");
		String message = request.getParameter("message");
		
		Properties p = new Properties(); // 정보를 담을 객체
		p.put("mail.smtp.host","gmail-smtp.l.google.com"); // 네이버 SMTP
		
		p.put("mail.smtp.port", "465");
		p.put("mail.smtp.starttls.enable", "true");
		p.put("mail.smtp.auth", "true");
		p.put("mail.smtp.debug", "true");
		p.put("mail.smtp.socketFactory.port", "465");
		p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		p.put("mail.smtp.socketFactory.fallback", "false");
		// SMTP 서버에 접속하기 위한 정보들
		
		//사용자가 관리자에게 문의를 하는 구조 - 결국 나에게 내가 이메일을 보낸다
		try{
		    Authenticator auth = new SMTPAuthenticator();
		    Session ses = Session.getInstance(p, auth);
		    
		    ses.setDebug(true);
		    
		    MimeMessage msg = new MimeMessage(ses); // 메일의 내용을 담을 객체
		    msg.setSubject(subject); // 제목
		    
		    Address fromAddr = new InternetAddress(email);
		    msg.setFrom(fromAddr); // 보내는 사람
		    
		    Address toAddr = new InternetAddress("didwodn8822@gmail.com");
		    msg.addRecipient(Message.RecipientType.TO, toAddr); // 받는 사람
		    
		    msg.setContent(email+"님께서 "+message, "text/html;charset=UTF-8"); // 내용과 인코딩
		    
		    Transport.send(msg); // 전송
		} catch(Exception e){
		    e.printStackTrace();
		    // 오류 발생시 뒤로 돌아가도록
		    System.out.println("error");
		}

		
		
		
		request.setAttribute("display","/main/location.jsp");
		
		return "/main/main.jsp";
	}

}

 

 

 

'Front-end > JSP' 카테고리의 다른 글

JSP Model2 (MVC)  (0) 2020.01.29