본문 바로가기
Runtime/Node.js

22. 메일링 서비스(이메일 보내기)

by 김엉배 2023. 4. 18.
728x90
반응형

 

1.  이메일 보내기

  • transporter 객체가 생성되면 sendMail 내장 함수를 사용해 이메일을 전송할 수 있다.
transporter.sendMail(data[, callback])

 

  • sendMail() 함수의 파라미터는 다음과 같다.
    - date : 이메일 메시지 전송을 위한 설정
        > from: 보내는 사람의 이메일 주소
        > to: 받는 사람 이메일 주소
        > cc: 참조 이메일 주소
        > bcc: 숨은 참조 이메일 주소
        > subject: 이메일 제목
        > text: 이메일 본문 내용을 일반 텍스트로 작성
        > html: 이메일 본문 내용을 HTML 문서로 작성
        > attachments: 첨부 파일
    - callback(err, info): 이메일 메시지 전송 혹은 전송 실패 시 호출되는 콜백 함수

2.  Gmail을 사용해 이메일 보내기 

 

  • 구글 보안 설정
    - 보안 수준이 낮은 앱의 액세스 허용
    - 내 Google 계정에 대한 액세스 허용

  • 구글 계정의 보안 메뉴로 이동 후 앱 비밀번호를 생성
      



 

앱 비밀번호 생성할 앱과 기기 선택


 

  • Gmail 계정과 앱 비밀번호를 사용해 nodemailer에서 이메일 전송(nodemailer 폴더에. env 파일 생성)
GOOGLE_MAIL = gmail주소
GOOLE_PASSWORD = 앱 비밀번호

 

  • nodemailer 폴더에 index.js 파일 생성 후 코드 작성
const nodemailer = require('nodemailer');

const config = {
  service: 'gmail',
  host: 'smtp.gmail.com', 
  port: 587,  
  secure: false, 
  auth: {
    user: process.env.GOOGLE_MAIL, // 구글 계정 메일
    pass: process.env.GOOGLE_PASSWORD, // 구글 계정 비밀번호 혹은 앱 비밀번호
  }
}

const send = async (data) => {
  const transporter = nodemailer.createTransport(config);
  transporter.sendMail(data, (err, info) => {
    if(err) {
      console.log(err);
    }else {
      return info.response;
    }
  });
}

module.exports = {
  send
}

 

  • nodemailer/index.js의 send() 함수를 사용해 이메일 전송하기 위해서 app_nodemailer.js 파일을 생성 후 코드 작성
const express = require("express");
require('dotenv').config({ path: 'nodemailer/.env' }); // nodemailer 폴더에 있는 
                                                       //.env 파일을 찾아서 환경변수를 설정
const nodemailer = require("./nodemailer"); // nodemailer 폴더의 index.js
const app = express();

app.use(express.json({
  limit: '50mb' // 최대 50메가
})); // 클라이언트 요청 body를 json으로 파싱 처리


app.listen(3000, () => {
  // 3000번 포트로 웹 서버 실행
  console.log('Server started. port 3000.');
});

// localhost:3000/api/email 라우트로 이메일 데이터를 post로 전송하면 nodemailer의 send 함수를 실행
app.post('/api/email', async (req, res) => {
  const r = await nodemailer.send(req.body.param);
  res.send(r); // 결과를 클라이언트로 보냄
});

 

  • Postman을 실행하고 Request를 추가하고 실행

 

  • Gmail 설정을 제대로 했다면 이메일이 정상적으로 발송되는 것을 확인할 수 있다.
728x90
반응형

'Runtime > Node.js' 카테고리의 다른 글

24. 작업 스케줄러(Job Scheduler)  (3) 2023.04.23
23. 메일링 서비스(mailtrap 서비스)  (2) 2023.04.19
21. 메일링 서비스(Nodemailer)  (7) 2023.04.18
20. 로그 관리  (2) 2023.04.18
19. MongoDB(스키마, 모델 생성)  (2) 2023.04.14