[Spring] Gmail 인증 메일 보내기

Java

Language :

1. gmail 계정 설정

gmail > 환경 설정 > 전달 및 pop/IMAP > IMAP 액세스 > IMAP 사용으로 변경 내 계정 >

로그인 및 보안 > 연결된 앱 및 사이트 > 보안 수준이 낮은 앱 허용 : 사용으로 변경

2. pom.xml

        <!-- GoogleMail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <!-- GoogleMail -->

3. root-context.xml

    <!-- Google Email -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com"/>
        <property name="port" value="587"/>
        <property name="username" value="googleId" />
        <property name="password" value="googlePassword"/>
        
        <property name="javaMailProperties">
            <props>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.debug">true</prop>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
            </props>
        </property>
    </bean>

4. EmailHandler.java

import java.io.UnsupportedEncodingException;
import java.util.Random;

import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class EmailHandler {

    private JavaMailSender mailSender;
    private MimeMessage msg;
    private MimeMessageHelper msgHelper;

    public EmailHandler() {}

    public EmailHandler(JavaMailSender mailSender) {
        try {
            this.mailSender = mailSender;
            msg = this.mailSender.createMimeMessage();
            msgHelper = new MimeMessageHelper(msg, true, "UTF-8");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public void setSubject(String subject) throws MessagingException {
        msgHelper.setSubject(subject);
    }

    public void setText(String htmlContent) throws MessagingException {
        msgHelper.setText(htmlContent, true);
    }

    public void setFrom(String email, String name) 
                throws UnsupportedEncodingException, MessagingException {
        msgHelper.setFrom(email, name);
    }

    public void setTo(String email) throws MessagingException {
        msgHelper.setTo(email);
    }

    public void addInline(String contentId, DataSource dataSource) throws MessagingException {
        msgHelper.addInline(contentId, dataSource);
    }

    public void send() {
        mailSender.send(msg);
    }

    // 인증키 랜덤
    public String randomKey() {
        StringBuffer key = new StringBuffer();
        Random rnd = new Random();

        for (int i = 0; i < 6; i += 1) {
            int rIndex = rnd.nextInt(2);

            switch (rIndex) {
            case 0:
                key.append((char) ((int) (rnd.nextInt(26)) + 65));
                break; // A-Z
            case 1:
                key.append(rnd.nextInt(10));
                break; // 0-9
            }
        }
        return key.toString(); // StringBuffer -> String
    }
}

5. Persistence.java

    @Autowired
    JavaMailSender mailSender;

    @Override
    public void sendGmail(String toEmail, String key) {
        try {
            EmailHandler sendMail = new EmailHandler(mailSender);
            
            sendMail.setSubject("회원가입 인증 메일");
            sendMail.setText(new StringBuffer().append("회원가입 인증 메일입니다<br>")
                .append("<a href='http://localhost:8080/spring/emailCheck?key=")
                .append(key)
                .append("' target='_blenk'>인증</a>").toString());
            
            sendMail.setFrom("FromMail", "FromName");
            sendMail.setTo(toEmail);
            sendMail.send();
            cnt = 1;
        } catch (Exception e) { 
            e.printStackTrace();
        }
    }

6. 인증 처리

Controller.java

    @RequestMapping("emailCheck")
    public String emailCheck(HttpServletRequest req, Model model) {
        System.out.println("emailCheck()");
        
        hs.confirmEmailKey(req, model);
        
        return "jsp/join/emailCheck";
    }

Service.java

    public void confirmEmailKey(HttpServletRequest req, Model model) {
        String key = req.getParameter("key");

        int cnt = dao.confirmEmailKey(key);

        model.addAttribute("cnt", cnt);
    }

Persistence.java

    @Override
    public int confirmEmailKey(String e_key) {
        int cnt = mapper.confirmEmailKey(e_key);
        return cnt;
    }

민갤

Back-End Developer

백엔드 개발자입니다.