카테고리 없음

nodemailer 사용해서 메일 보내기

EUNJI HA 2020. 9. 17. 16:53

비밀번호 재설정 API를 구현하려고 한다. 

 

node.js에는 nodemailer라는 라이브러리가 있다. 

 

현재 async, await 때문에 발생하는 오류 해결을 못했지만, 간단한 nodemailer 사용은 구현되어 정리.

 

먼저 공식 사이트에 있는 예시코드

// async..await is not allowed in global scope, must use a wrapper
async function main() {
  // Generate test SMTP service account from ethereal.email
  // Only needed if you don't have a real mail account for testing
  let testAccount = await nodemailer.createTestAccount();

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: testAccount.user, // generated ethereal user
      pass: testAccount.pass, // generated ethereal password
    },
  });

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: '"Fred Foo 👻" <foo@example.com>', // sender address
    to: "bar@example.com, baz@example.com", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world?", // plain text body
    html: "<b>Hello world?</b>", // html body
  });

  console.log("Message sent: %s", info.messageId);
  // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

  // Preview only available when sending through an Ethereal account
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

main().catch(console.error);

1. Gmail 계정에서 보낼 경우, 보안 설정을 변경해야 한다. 

gaemi606.tistory.com/42

 

https://myaccount.google.com/lesssecureapps
https://accounts.google.com/DisplayUnlockCaptcha

이 설정을 안하게 될 경우 구글로 부터 이런 메일을 받게됨 ㅋㅋ

 

2. nodemailer getaddrinfo ENOTFOUND Error 해결

stackoverflow.com/questions/46357348/nodemailer-getaddrinfo-enotfound-error

 

var smtpTransport = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL
    auth: {
        user: 'user@gmail.com',
        pass: 'pass'
    }
});

 

 

대략 이런 식으로 구현 하고 API 통신을 하면 

// Controller 중 일부
exports.mailer = async function (req, res) {

	// 클라로부터 받을 이메일. to에 넣을 예정
    let {email} = req.body;

	// 유효성 검사 코드 ~~~


    // Generate test SMTP service account from ethereal.email
    // Only needed if you don't have a real mail account for testing
    // let testAccount = await nodemailer.createTestAccount();
  
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
      host: "smtp.gmail.com",
      port: 465,
        secure: true, // use SSL
      // port: 587,
      // secure: false, // true for 465, false for other ports
      auth: {
        user: '<FROM의 email>', // generated ethereal user
        pass: '<FROM의 Password>', // generated ethereal password
      },
    });
  
    // send mail with defined transport object
    let info = await transporter.sendMail({
      from: '<FROM의 이메일>', // sender address
      to: "<TO의 이메일>", // list of receivers
      subject: "Hello ✔", // Subject line
      text: "Hello world?", // plain text body
      html: "<b>Hello world?</b>", // html body
    });
  
    console.log("Message sent: %s", info.messageId);
    // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
  
    // Preview only available when sending through an Ethereal account
    console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
    // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...

    return res.json(
        {isSuccess: true, code: 200, message: "성공"});


}

이렇게 메일이 오는 것을 확인할 수 있다.