KUKJIN LEE's profile picture

KUKJIN LEE

Posted time

Posted 2 months ago

Nodemailer로 이메일 전송하기: 초보 개발자를 위한 가이드

Node.js 환경에서 이메일을 전송하는 가장 간편한 방법 중 하나는 Nodemailer를 사용하는 것입니다.

 

1. Nodemailer란?

Nodemailer는 Node.js 애플리케이션에서 이메일을 전송할 수 있게 도와주는 모듈입니다. SMTP(Simple Mail Transfer Protocol)를 통해 이메일을 보내며, 설정과 사용이 매우 간단합니다.

 

2. Nodemailer 설치하기

먼저 프로젝트 디렉토리에서 Nodemailer를 설치합니다. 다음 명령어를 사용하여 Nodemailer를 설치합니다.

 

npm install nodemailer

 

3. 기본 사용 방법

설치가 완료되면, Nodemailer를 사용하여 이메일을 보낼 수 있습니다. 여기서는 Gmail을 사용하여 이메일을 보내는 예제를 설명하겠습니다.

  1. SMTP 설정: Gmail SMTP 서버를 사용하여 이메일을 전송합니다. Gmail 계정의 보안을 위해 앱 비밀번호를 사용하는 것이 좋습니다.

  2. 이메일 전송 코드 작성: Nodemailer 설정과 이메일 전송을 위한 기본 코드를 작성합니다.

 

 

※ PASS Key는 반드시 .env에 넣어주세요.

const nodemailer = require('nodemailer');
// SMTP 설정
let transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'your-email@gmail.com', // 발신자 이메일 주소
    pass: 'your-email-password',  // 발신자 이메일 비밀번호 (앱 비밀번호)
  },
});
// 이메일 옵션 설정
let mailOptions = {
  from: 'your-email@gmail.com', // 발신자 이메일 주소
  to: 'recipient-email@example.com', // 수신자 이메일 주소
  subject: 'Hello from Nodemailer', // 이메일 제목
  text: 'This is a test email sent using Nodemailer.', // 이메일 내용 (텍스트)
  // html: '<h1>This is a test email sent using Nodemailer.</h1>', // 이메일 내용 (HTML)
};
// 이메일 전송
transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    return console.log(error);
  }
  console.log('Email sent: ' + info.response);
});

 

4. 환경 변수 사용하기

보안상의 이유로 이메일과 비밀번호를 코드에 직접 입력하는 것은 좋지 않습니다. 대신 환경 변수를 사용하여 설정합니다. 프로젝트 루트에 .env 파일을 생성하고 다음 내용을 추가합니다.

 

GMAIL_USER=your-email@gmail.com
GMAIL_PASS=your-email-password

 

5. Next.js와 Nodemailer 사용하기

Next.js 프로젝트에서 Nodemailer를 사용하여 이메일을 전송하는 방법도 매우 간단합니다. Next.js의 API 라우트를 사용하여 이메일 전송을 처리할 수 있습니다. app/api/sendEmail.js 파일을 생성하고 다음과 같이 작성합니다.

import nodemailer from 'nodemailer';
export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { to, subject, text } = req.body;
    let transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: process.env.GMAIL_USER,
        pass: process.env.GMAIL_PASS,
      },
    });
    let mailOptions = {
      from: process.env.GMAIL_USER,
      to: to,
      subject: subject,
      text: text,
    };
    try {
      await transporter.sendMail(mailOptions);
      res.status(200).json({ message: 'Email sent successfully' });
    } catch (error) {
      res.status(500).json({ message: 'Failed to send email', error: error.message });
    }
  } else {
    res.status(405).json({ message: 'Method not allowed' });
  }
}

Nodemailer는 Node.js 환경에서 이메일을 전송하는 데 매우 유용한 모듈입니다. 쉽게 설치하고 사용할 수 있으며, 다양한 이메일 전송 옵션을 제공합니다. 이 가이드를 통해 Nodemailer의 기본 사용 방법을 익히고, 이메일 전송 기능을 프로젝트에 추가할 수 있습니다.

 

New Tech Posts