build.gradle


//email
implementation 'org.springframework.boot:spring-boot-starter-mail'

 

application-properties


spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=gmail 아이디
spring.mail.password=gamil 패스워드
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true

 

EmailController.java


package com.chatting.controller;

import com.chatting.common.Url;
import com.chatting.util.EmailUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;

/**
 * 이메일 컨트롤러
 */

@Slf4j
@RequiredArgsConstructor
@RestController
public class EmailController {

    private final EmailUtil emailUtil;

    /**
     * 이메일 발송
     * @param params
     * @return
     */
    @PostMapping(Url.AUTH.SEND_EMAIL)
    public Map<String, Object> sendEmail(@RequestBody Map<String, Object> params){
        log.info("email params={}", params);

        return emailUtil.sendEmail( (String) params.get("userId")
                , (String) params.get("subject")
                , (String) params.get("body")
        );
    }
}

userId : 보낼 이메일 아이디

subject : 이메일 제목

body : 이메일 내용

 

EmailUtil.java


package com.chatting.util;

import java.util.Map;

public interface EmailUtil {
    Map<String, Object> sendEmail(String toAddress, String subject, String body);
}

 

EmailUtilImpl.java


package com.chatting.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

@Component
public class EmailUtilImpl implements EmailUtil {

    @Autowired
    private JavaMailSender sender;

    @Override
    public Map<String, Object> sendEmail(String toAddress, String subject, String body) {
        Map<String, Object> result = new HashMap<String, Object>();
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            helper.setTo(toAddress);
            helper.setSubject(subject);
            helper.setText(body);
            result.put("resultCode", 200);
        } catch (MessagingException e) {
            e.printStackTrace();
            result.put("resultCode", 500);
        }

        sender.send(message);
        return result;
    }
}

 

gmail smtp 서버에 접근할수 있게 설정을 해줘야되는 부분이 있는데 

하는 방법은 아래 링크에 공유드립니다.

 

https://support.google.com/mail/answer/7126229?hl=ko 

 

다른 이메일 플랫폼을 통해 Gmail 확인하기 - Gmail 고객센터

도움이 되었나요? 어떻게 하면 개선할 수 있을까요? 예아니요

support.google.com

 

script

 
 //이메일 발송
    emailSend();

    //이메일 발송
    function emailSend(){
        var serialNo = generateRandomCode(6);
        var subject = "chats 회원인증번호 입니다.";
        var body = "안녕하세요 chats 입니다. \n 회원가입 인증번호는" +serialNo+ " 입니다.";

        var params = {
             userId : $("#userId").val()
            ,subject : subject
            ,body : body
        }

        if(serialNo == ""){
            alert("인증번호를 입력해주세요.");
            return false;
        }

        $.ajax({
            url: "/auth/sendEmail"
            ,type: "POST"
            ,accept: "application/json"
            ,contentType: "application/json; charset=utf-8"
            ,data: JSON.stringify(params)
            ,dataType: "json"
            ,success: function(data) {

                //시리얼번호 db에 저장
                saveSerialNo(serialNo)
            },

            error: function(jqXHR,textStatus,errorThrown) {
                alert("이메일 전송에 실패하였습니다.");
            }
        });
    }

 

결과

 

복사했습니다!