본문 바로가기

Web Dev

Node.js 백엔드에서 메일 전송하기 (with Nodemailer & Gmail)

반응형

 

https://www.npmjs.com/package/nodemailer

 

nodemailer

Easy as cake e-mail sending from your Node.js applications. Latest version: 6.9.1, last published: 10 days ago. Start using nodemailer in your project by running `npm i nodemailer`. There are 5765 other projects in the npm registry using nodemailer.

www.npmjs.com

 

 

npm i nodemailer

 

https://nodemailer.com/about/

 

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

nodemailer.com

doc 참고 하는게 좋다 

 

 

 

구글 설정에 들어가서 -> 보안 -> 2단계 인증을 꼭 ! 받아야한다. 

이와 같이 진행하면 -> utncdeagdotdillg 

이와 같은 비밀번호가 생성된다. .env 파일을 생성하여 해당 파일에 객체 형태로 입력해주고 -> 함수를 통해서 메일 보내는 api를 만들어주면 됩니다.예시)index.js

 

app.post('/users', (req, res) => {

    const user = req.body.myuser


    //1. 이메일 존재여부 확인하기 
    const isValid = checkValidationEmail(user.email);

    if (isValid) {
        //2. 가입환영 템플릿 만들기
        const myTemplate = getWelcomeTemplate(user)
        //3. 이메일에 가입환영 템플릿 전송하기 
        sendTemplateToEmail(user.email, myTemplate);
        res.send('가입 완료!!!');

    }

 

 

email.js

결과 값을 확인하기 위해 <동기>로 작성 

 

export async function sendTemplateToEmail(email, myTemplate) {


    const EMAIL_USER = process.env.EMAIL_USER
    const EMAIL_PASS = process.env.EMAIL_PASS
    const EMAIL_SENDER = EMAIL_USER

    const transporter = nodemailer.createTransport({
        service: "gmail",
        // host: "smtp.ethereal.email",
        // port: 587,
        // secure: false, // true for 465, false for other ports
        auth: {
            user: EMAIL_USER, // generated ethereal user
            pass: EMAIL_PASS, // generated ethereal password
        },

    });

    const result = await transporter.sendMail({
        from: EMAIL_SENDER,
        to: email,
        subject: "[CentumJoonho] 가입을 축하합니다.",
        html: myTemplate
    })
    console.log(result);

    // console.log(email + " 메일로 " + myTemplate + "를 전송합니다 !! ");
}

 

 

 

 

 

 

{
   "myuser":{"name": "철수",
    "age": 8,
    "school": "다람쥐 초등학교",
    "email": "ghwnsgkgk@kakao.com"} 
}

 

 postman으로 작성해서 api에 post로 발송하여 : 가입완료 응답을 받았으나 backend에서는 에러가 발생했다. 

Error: Missing credentials for "PLAIN"
    at SMTPConnection._formatError (/home/centumjoonho/joonho/nodejs/nodejs_inflearn/nodejs_inflearn_backend/class/03-01-axios-rest-api-email/back/node_modules/nodemailer/lib/smtp-connection/index.js:790:19)
    at SMTPConnection.login (/home/centumjoonho/joonho/nodejs/nodejs_inflearn/nodejs_inflearn_backend/class/03-01-axios-rest-api-email/back/node_modules/nodemailer/lib/smtp-connection/index.js:444:38)
    at /home/centumjoonho/joonho/nodejs/nodejs_inflearn/nodejs_inflearn_backend/class/03-01-axios-rest-api-email/back/node_modules/nodemailer/lib/smtp-transport/index.js:272:32
    at SMTPConnection.<anonymous> (/home/centumjoonho/joonho/nodejs/nodejs_inflearn/nodejs_inflearn_backend/class/03-01-axios-rest-api-email/back/node_modules/nodemailer/lib/smtp-connection/index.js:213:17)
    at Object.onceWrapper (node:events:627:28)
    at SMTPConnection.emit (node:events:513:28)
    at SMTPConnection._actionEHLO (/home/centumjoonho/joonho/nodejs/nodejs_inflearn/nodejs_inflearn_backend/class/03-01-axios-rest-api-email/back/node_modules/nodemailer/lib/smtp-connection/index.js:1331:14)
    at SMTPConnection._processResponse (/home/centumjoonho/joonho/nodejs/nodejs_inflearn/nodejs_inflearn_backend/class/03-01-axios-rest-api-email/back/node_modules/nodemailer/lib/smtp-connection/index.js:953:20)
    at SMTPConnection._onData (/home/centumjoonho/joonho/nodejs/nodejs_inflearn/nodejs_inflearn_backend/class/03-01-axios-rest-api-email/back/node_modules/nodemailer/lib/smtp-connection/index.js:755:14)
    at SMTPConnection._onSocketData (/home/centumjoonho/joonho/nodejs/nodejs_inflearn/nodejs_inflearn_backend/class/03-01-axios-rest-api-email/back/node_modules/nodemailer/lib/smtp-connection/index.js:193:44) {
  code: 'EAUTH',
  command: 'API'
}

 

아 제가 .env 파일을 쓰면서 dotenv 라이브러리를 까먹었네요 ! 

https://www.npmjs.com/package/dotenv

 

dotenv

Loads environment variables from .env file. Latest version: 16.0.3, last published: 4 months ago. Start using dotenv in your project by running `npm i dotenv`. There are 32628 other projects in the npm registry using dotenv.

www.npmjs.com

설치를 제대로 해주고

 

 

import * as dotenv from 'dotenv' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
dotenv.config()

import 해줍니다. 

 

 

{
  accepted: [ 'ghwnsgkgk@kakao.com' ],
  rejected: [],
  ehlo: [
    'SIZE 35882577',
    '8BITMIME',
    'AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH',
    'ENHANCEDSTATUSCODES',
    'PIPELINING',
    'CHUNKING',
    'SMTPUTF8'
  ],
  envelopeTime: 938,
  messageTime: 920,
  messageSize: 893,
  response: '250 2.0.0 OK  1675692794 z9-20020a170903018900b00188fadb71ecsm6963964plg.16 - gsmtp',
  envelope: { from: 'ghwnsgkgkgk@gmail.com', to: [ 'ghwnsgkgk@kakao.com' ] },
  messageId: '<f703d0c3-f402-9aea-4a22-2667b9f77626@gmail.com>'
}

잘 보내졌다는 응답 메세지 확인 가능합니다. 

 

 

이렇게 데이터가 메일로 잘 날라옵니다. 

html 수정도 가능합니다 + style css

 

 

export function getWelcomeTemplate({ name, age, school }) {
    return (`
        <html>
        <body style ="width : 500px">
        <h1 style="color : blue">${name}님 가입을 환영합니다. </h1>
        <hr/>
        <div>이름 : ${name}</div>
        <div>나이 : ${age}</div>
        <div>학교 : ${school}</div>
        <div>가입 : ${getToday()}</div>

        </body>
        </html>`
    )

}

mail 플랫폼에따라 css를 인식하는 정도가 달라서 

최신 css 보다는 예전 css를 사용하는게 좋다고 합니다. 

 

 

반응형