최근 들어서는 Nodemailer 보다는 그냥 mailgun-js를 사용하고 있습니다.
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. Tryin
nodemailer.com
nodemailer는 다운로드 수가 주간 1,000,000. (매우 높은 수치)입니다.
npm i nodemailer
문제는 transport이다. 메일을 보내주는 서비스를 골라서 이용해야 하는 것이다. 공식 문서에는 기본 값으로 SMTP transport이 있다고 하는데 해보면 알겠지만 개발자의 인내심을 테스트하는 녀석입니다. 외부 transports를 이용하는 게 속 편합니다.
외부 transports로 유명한 서비스로는 mailgun, AWS SES등이 있습니다. mailgun을 이용해봅시다.
nodemailer-mailgun-transport
A transport module to use with nodemailer to leverage Mailgun's REST API
www.npmjs.com
npm i nodemailer-mailgun-transport
mailgun은 메일을 보내기 위해 API와 Domain을 요구합니다. 메일건에 접속해서 해당 api 키와 Domain을 긁어옵시다. 여기서 주의할 점은 /v3/... 이후 내용만 첨부해야 한다는 것입니다. 모든 주소를 다 입력하면 오류를 일으킵니다.
해당 정보를 env에 넣어놓고 메일을 보내는 동작을 구현했습니다.
import dotenv from "dotenv";
import path from "path";
dotenv.config({ path: path.resolve(__dirname, ".env") });
import nodemailer from "nodemailer";
import mgTransport from "nodemailer-mailgun-transport";
// 이메일을 보내는 논리적인 동작을 구현했습니다.
const sendMail = (email) => {
const options = {
auth: {
api_key: process.env.MAILGUN_API,
domain: process.env.MAILGUN_DOMAIN,
},
};
const client = nodemailer.createTransport(mgTransport(options));
return client
.sendMail(email)
.then(() => {
console.log("Message sent!");
})
.catch((error) => {
console.log(error);
});
};
// 메일에 대한 내용을 다룹니다. sendMail을 통해 메일을 보냅니다.
export const sendSecretMail = (address, secret) => {
const email = {
from: "test@edupopkorn.com",
to: address,
subject: "Login Secret for Prismagram 🚀",
html: `<h1>hello! your login secret is ${secret}.</h1>
<h2>Copy paste on the web/app to Login</h2>`,
};
return sendMail(email);
};
// 메일을 보냈습니다. 메일함을 체크합시다
sendSecretMail("whogotthismail@gmail.com", "whatever")
메일 보내는 동작을 이벤트 리스너에 등록하는 등 조작해서 특정 상황에 메일을 보내도록 코딩하면 됩니다.
저는 graphql+apollo 조합을 사용할 때 Mutation에 추가해보았습니다.
import { generateSecret, sendSecretMail } from "../../../utils";
import { prisma } from "../../../../generated/prisma-client";
export default {
Mutation: {
requestSecret: async (_, args) => {
const { email } = args;
const loginSecret = generateSecret();
try {
await sendSecretMail(email, loginSecret);
await prisma.updateUser({ data: { loginSecret }, where: { email } });
return true;
} catch (error) {
return false;
}
},
},
};
'Node, Nest, Deno > 🚀 Node.js (+ Express)' 카테고리의 다른 글
multer-S3를 이용한 동영상, 이미지 저장 (0) | 2020.04.30 |
---|---|
Express로 REST API 구성하기 (0) | 2020.04.27 |
React-Express에서 AWS RDS(DB 서버)로 데이터 전송하기 (0) | 2020.04.09 |
React 프론트를 Express 백엔드와 연결하기 (0) | 2020.04.08 |
npm 업데이트와 node 업데이트 (nvm, n) (0) | 2020.04.04 |