본문 바로가기

Project 기록/와글와글(web)

[프로젝트] nodemailer 사용해서 인증번호 확인 해보자 ① (react)

728x90
반응형

회원가입을 할 때 이메일을 보낸 후 인증번호를 확인 할 때가 있다

 

감사하게도 구글에서 nodemailer API를 지원해준다. 빨리 해보자!!!

 

 

만들고 있는 회원가입 form 이다

 

'전송'버튼을 누르면 클라이언트에게 텍스트가 전송 되게 해볼 것이다


 

우선 구글 아이디에 설정이 몇 개 필요하다

https://accounts.google.com/DisplayUnlockCaptcha

 

요기로 가서 허용 해주자

https://accounts.google.com/DisplayUnlockCaptcha

 

요기도 방문해 주자 '계속'클릭

 

 

 

이메일을 보낼 계정 세팅은 끝났다 


 

nodemailer를 사용할 모듈이 필요하다

 

npm install nodemailer --save

설치 해주자

 

 

 

 

버튼 누르고 서버에게 요청 할 클라이언트.js 코드다

 

 

<button onClick={this.sendEmail}> 전송 </button>

위 의 버튼을 누르면 

 

아래의 이벤트 함수가 발동 된다. 아직 구체적인 내용은 안 썼고 메일 부터 보내지는지 보자

 

class Signup_page extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            email: '',           // 입력받은 email state값

        }
        this.sendEmail = this.sendEmail.bind(this);
    
    }
    

    sendEmail(e){
        e.preventDefault();
        console.log(this.state.email);
        const data = {                      //현재의 email state값을 data객체로 감쌌다
            email: this.state.email
        }

        fetch('http://localhost:3001/sendEmail',{      //sendEmail 라우터로 보내버리기
            method: "post",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(data),
        })
        .then(res => res.json())
        .then(json => {
            
        })
        
    }

   

 

 

 

 

server쪽 js 파일이다

 

let nodemailer = require('nodemailer');    //노드메일러 모듈을 사용할 거다!



router.post('/sendEmail', async function (req, res) {


    let user_email = req.body.email;     //받아온 email user_email에 초기화

    console.log(user_email);


    // 메일발송 함수

    let transporter = nodemailer.createTransport({
        service: 'gmail'              //사용하고자 하는 서비스
        , prot: 587
        , host: 'smtp.gmlail.com'
        , secure: false
        , requireTLS: true
        , auth: {
            user: '구글@gmail.com'           //gmail주소입력
            , pass: '비밀번호1234'                 //gmail패스워드 입력
        }
    });

    let info = await transporter.sendMail({   
        from: '구글@gmail.com',             //보내는 주소 입력
        to: user_email,                        //위에서 선언해준 받는사람 이메일
        subject: '안녕하세요',                  //메일 제목
        text: 'ㅁㄴㅇㄹ',                       //내용
      });


})

 

 


결과: 

 

이메일 입력 후 전송을 누르면 

 

 

작고 귀여운 메일이 도착해 있다

 

 

와우!!!!!

 

다음 포스트는 랜덤으로 인증번호 생성 한 뒤 일치 하는 지 알아보자 !!

 

 

 

 

반응형