Promise를 사용한 이메일 발송 기능 개발
이메일은 현대 비즈니스에서 필수적인 커뮤니케이션 도구입니다. Node.js에서는 nodemailer
와 같은 라이브러리를 사용하여 이메일 발송 기능을 구현할 수 있습니다. 이번 기사에서는 nodemailer
를 활용하여 Promise를 사용한 이메일 발송 기능을 개발하는 방법에 대해 알아보겠습니다.
단계 1: nodemailer 설치
먼저 nodemailer
를 설치해야 합니다. 프로젝트 폴더에서 다음 명령어를 실행하여 nodemailer를 설치합니다.
npm install nodemailer
단계 2: 이메일 발송 코드 작성
다음으로, 이메일 발송을 위한 코드를 작성해보겠습니다. smtpTransport
를 설정하고, 발신자, 수신자, 제목 및 본문을 설정하는 단계를 거치게 됩니다.
먼저, 다음과 같이 nodemailer
를 import 합니다.
const nodemailer = require('nodemailer');
다음 예시처럼 이메일 발송 함수를 만들어 보겠습니다.
function sendEmail() {
// SMTP transporter 생성
const transporter = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: 'sender@example.com',
pass: 'password',
},
});
// 이메일 구성
const mailOptions = {
from: 'sender@example.com',
to: 'recipient@example.com',
subject: 'Hello from Node.js',
text: 'This is a test email sent from Node.js using nodemailer.',
};
// 메일 전송
transporter.sendMail(mailOptions)
.then((info) => {
console.log('Email sent: ' + info.response);
})
.catch((error) => {
console.log('Error:', error);
});
}
단계 3: 이메일 발송 함수 호출
이제 sendEmail
함수를 호출하여 이메일을 발송해보겠습니다. 다음과 같이 코드를 추가해주세요.
sendEmail();
마치며
위의 단계들을 따라가면 Promise를 사용하여 Node.js에서 이메일 발송 기능을 개발할 수 있습니다. nodemailer
를 사용하면 SMTP를 통해 이메일을 발송하는 과정을 간단하게 처리할 수 있습니다.
해당 기능을 사용하면 비동기적으로 이메일을 발송하고, 성공적으로 발송되었는지 여부를 확인할 수 있습니다. 비즈니스 애플리케이션에서는 이메일 발송 기능이 매우 중요하므로, 유용하게 활용할 수 있을 것입니다.
#email #NodeJS