NestJS, mailgun 이용하기
2022. 10. 12. 14:14ㆍ개발/Node
NestJS에서 mailgun을 사용하는 기본 방법입니다.
여기서는 mailgun document에 있는 가장 기본적인 보내는 방법을 설명합니다.
https://documentation.mailgun.com/en/latest/quickstart-sending.html#send-with-smtp-or-api
먼저 mailgun.js, form-data를 사용하기 위해 패키지를 설치합니다.
yarn add mailgun.js
yarn add form-data
mailgun.service.ts
secret key를 가져오고 실제로 발송하는 부분을 Service로 분리하였습니다.
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Mailgun from 'mailgun.js';
import FormData from 'form-data';
@Injectable()
export class MailgunService {
constructor(private readonly config: ConfigService) {}
// mailgun secret key
private MAILGUN_KEY = this.config.get<string>('MAILGUN_KEY');
private MAILGUN_DOMAIN = this.config.get<string>('MAILGUN_DOMAIN');
private client = new Mailgun(FormData).client({
username: 'api',
key: this.MAILGUN_KEY,
});
/**
* Send via API
*
* @param data
*/
async sendMail(data) {
this.client.messages
.create(this.MAILGUN_DOMAIN, data)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.error(err);
});
}
}
app.controller.ts
메일을 발송하는 API는 app controller에 구현했으며 MailgunService를 가져와서 실행합니다.
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { MailgunService } from './providers/mailgun/mailgun.service';
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
private readonly mailgunService: MailgunService,
) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@Get('mail')
getMail() {
const messageData = {
from: 'Excited User <me@samples.mailgun.org>',
to: 'foo@example.com, bar@example.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomeness!',
};
this.mailgunService.sendMail(messageData);
}
}
esModuleInterop
위 코드만 구현해서 실행하면 this.FormDataConstructor is not a constructor 메세지와 함께 TypeError가 생길 수 있습니다.
이를 방지하기 위해 tsconfig.json에 esModuleInterop를 true로 추가합니다.
그 후 실행하면 'Queued. Thank you.' 메시지를 받을 수 있습니다.
전체 코드는 github에 공개합니다.
https://github.com/calc2te/nestjs-mailgun
'개발 > Node' 카테고리의 다른 글
NestJS, TypeORM 적용하기 (nestjs + typeorm + env) (0) | 2023.02.09 |
---|---|
NestJS, typeORM relation에서 다른 컬럼 이름을 사용하기 (0) | 2022.10.31 |
NestJS, DynamoDB에 있는 글들을 hbs에서 보여주기 (0) | 2021.07.27 |
NestJS, 과제 사이트를 만들고 난 느낌 (0) | 2021.07.07 |
NestJS, 파일 읽기 (0) | 2021.06.24 |