본문 바로가기
Study(매일매일한걸음씩)/Web(html,css,js)

node js로 메일 보내기(gmail) #1 -vsc

by 여유러운백수삶개발자 2024. 4. 4.
node js로 메일 보내기 구현

 

  1. file 만들기
    1. server.js
    2.  
  2. nodemailer 설치
npm install nodemailer

 

pasckage.json : nodemailer 설치 완료

https://www.nodemailer.com/

 

Nodemailer :: Nodemailer

Nodemailer Nodemailer is a module for Node.js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, today it is the solution most Node.js users turn to by default. npm i

www.nodemailer.com

 

 


coding

1. 불러오기(nodemailer) - server.js 에 추가

const nodemailer = require('nodemailer');

2. 발송하는 사람 data 추가

const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'xxxxxxx@gmail.com', // 보내는 사람 이메일
            pass: 'xxxxxxxxx' // 보내는 사람 이메일의 비밀번호
        }
    });

3. 받는 내용 작성

const mailOptions = {
        from: 'xxxxxxxx@gmail.com', // 보내는 사람 이메일
        to: xxxxxxxxx, // 받는 사람 이메일
        subject: xxxxxxxx,
        text: 'Node.js에서 이메일을 보내는 테스트 중입니다.', // 텍스트 내용
        // attachments: []
    };

4. 메일 발송

transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            console.error('이메일 전송 중 오류 발생:', error);
            res.status(500).send('이메일 전송 중 오류 발생');
        } else {
            console.log('이메일 전송 완료:', info.response);
            res.send('이메일 전송 완료');
        }
    });

5. gmail 암호 확인(gmail 비밀번호를 그냥 넣는것이 아니라 앱 비밀번호 따로 만들어서 해야 된다) - 오류 발생한다.

* 4자리 4개 나오는데 띄어쓰기도 포함해서 복사한다.

- 계정관리 클릭

- 앱 비밀번호(그냥 검색이 편하다)

- 비밀번호 만들기(복사)

const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'xxxxxxx@gmail.com', // 보내는 사람 이메일
            pass: 'xxxxxxxxx' // 보내는 사람 이메일의 비밀번호
        }
    });

pass 에 입력한다.

 

 


const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'xxxxxxxxx@gmail.com', // 보내는 사람 이메일
        pass: 'xxxx xxx ptjc hqgy' // 보내는 사람 이메일의 비밀번호
    }
});

const mailOptions = {
    from: 'xxxxxxxxx@gmail.com', // 보내는 사람 이메일
    to: "xxxxxxxx@gmail.com", // 받는 사람 이메일
    subject: "[test] ",
    text: 'Node.js에서 이메일을 보내는 테스트 중입니다.....', // 텍스트 내용
    // attachments: []
};

transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
        console.error('이메일 전송 중 오류 발생:', error);
        res.status(500).send('이메일 전송 중 오류 발생');
    } else {
        console.log('이메일 전송 완료:', info.response);
        res.send('이메일 전송 완료');
    }
});

실행

node server.js

메일 확인(잘 옴) - daum 메일로도 잘감

 

댓글