본문 바로가기

Backend/Node.js

Node.js 메일 발송 (nodemailer)

NodeJS에서 메일을 발송해볼게요.

발송자 메일은 Google 기준으로 작성했어요.

혹시 다른 사이트의 메일로 발송을 원하시는데 어려움을 겪고 계시다면 댓글 남겨주시면 제가 한 번 찾아볼게요!

 

저는 nodemailer를 이용했어요.

일단 nodemailer를 설치해줍니다.

 

npm install nodemailer

 

그리고 transport 객체를 생성하는 파일을 만들어줄거에요.

이 객체로 우리는 비즈니스 로직을 구현할거에요.

저는 mail.transport.js 라는 파일을 만들어서 transport 객체를 만들고 export 했습니다.

mail.transport.js

const nodemailer = require('nodemailer')

const transport = nodemailer.createTransport({
  service: 'gmail',
  host: 'smtp.gmail.com',
  port: 465,
  secure: true,
  auth: {
    user: 'abc@gmail.com',
    pass: 'abc1234!',
  },
})

module.exports = transport

 

이제 메일을 발송할 준비는 끝났어요.

router에서 직접 메일을 발송해볼게요.

 

users.route.js

const express = require('express')
const router = express.Router()
const transport = require('../plugins/mail.transport')

router.post('/emails/:email/certification', (req, res, next) => {
  const { email } = req.params

  transport.sendMail({
    from: `ABC <hkhong91@gmail.com>`,
    to: email,
    subject: '[ABC] 인증번호가 도착했습니다.',
    text: '123456',
    html: `
      <div style="text-align: center;">
        <h3 style="color: #FA5882">ABC</h3>
        <br />
        <p>123456</p>
      </div>
    `})
    .then(send => res.json(send))
    .catch(err => next(err))
})

 

nodemailer 계정정보가 틀렸을 때 아래와 같은 오류를 확인할 수 있어요.

혹은 보안 수준이 낮은 앱의 액세스가 허용되지 않을 경우도 동일한 오류가 발생할거에요.

계정정보가 먼저 정확한지 확인해주시고, 아래 링크를 한 번 읽어보세요.

그리고 보안 수준의 낮은 앱의 액세스를 허용하시고 다시 호출하시면 성공할거에요.

 

{
  "code": "EAUTH",
  "response": "535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8  https://support.google.com/mail/?p=BadCredentials r1sm18610549pfh.2 - gsmtp",
  "responseCode": 535,
  "command": "AUTH PLAIN"
}

https://support.google.com/mail/?p=BadCredentials

 

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

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

support.google.com

 

성공했을 때에 콜백 받은 데이터입니다.

 

{
  "accepted": [
    "gofnrk@nate.com"
  ],
  "rejected": [],
  "envelopeTime": 813,
  "messageTime": 1229,
  "messageSize": 769,
  "response": "250 2.0.0 OK  1611670553 s18sm2486078pjr.14 - gsmtp",
  "envelope": {
    "from": "hkhong91@gmail.com",
    "to": [
      "gofnrk@nate.com"
    ]
  },
  "messageId": "<dfda3b95-9a9d-f23c-4f22-96ea00790ec2@gmail.com>"
}

 

실제로 수신자 메일을 확인해보니 메일이 도착해있네요!

HTML 형식도 잘 적용되있어요.