이메일 인증(1) nodemailer 사용법

Creating the dots·2021년 10월 10일
0

project-1-dagachi

목록 보기
8/11

nodemailer

In order to send messages, those three would be following.

  • Create a nodemailer transporter using either SMTP or some other transport mechanism
  • Set up message options (who sends what to whom)
  • Deliver the message object using the sendMail() method of your previously created transporter

nodemailer 설치하고 transporter 객체 생성하기

//install Nodemailer from npm
npm install nodemailer

//generate SMTP service account from etherea.email
const nodemailer = require("../lib/nodemailer");
nodemailer.createTestAccount((err, account) => {
  if(err){
    console.err('Failed to create a testing account');
    console.err(err);
    return process.exit(1);
  }
  
  console.log('Credentials obtained, sending message...');


//create a SMTP transporter object (to send emails you need a transporter object)
let transporter = nodemailer.createTransport(transport[, defaults]);

//defining transport와 default 
let transporter = nodemailer.createTransport({
  host: account.smtp.host;
  port: account.smtp.port,
  secure: account.smtp.port,
  auth: {
  user: account.user,
  pass: account.pass
  },
  logger: true,
  transactionLog: true
},
{ //default message fields
  //sender info
  from: 'Nodemailer <example@nodemailer.com>',
});
  • transporter: an object that is able to send email
  • transport: the transport configuration object
  • defaults: an object that defines default values for mail options

메시지 옵션 작성하고 이메일 전송하기

//Once you have a transporter object you can send mail with it
const message = {
  to: 'Nodemailer <example@nodemailer.com>',
  subject: 'Nodemailer is unicode friendly ✔' + Date.now(),
  text: 'Hello to myself',
  html: '<p><b>Hello</b> to myself</p>',
  amp: `<!doctype html>
        <html ⚡4email>
          <head>
            <meta charset="utf-8">
            <style amp4email-boilerplate>body{visibility:hidden}</style>
            <script async src="https://cdn.ampproject.org/v0.js"></script>
            <script async custom-element="amp-anim" src="https://cdn.ampproject.org/v0/amp-anim-0.1.js"></script>
          </head>
          <body>
            <p><b>Hello</b> to myself</p>
          </body>
        </html>`,
}
transporter.sendMail(data[, callback]);
transporter.sendMail(message, (error, info)=>{
  if(error){
    console.log('Error occurred');
    console.log(error.message);
    return process.exit(1);
  }
  console.log('Message sent successfully!');
  console.log(nodemailer.getTestMessageUrl(info));
  
  //only needed when using pooled connections
  transporter.close();
});
});
  • data: 필수 전송할 메일 내용
  • callback: 옵션 메시지가 전송에 성공하거나 실패했을때 동작하는 함수
    • err: 메시지 전송에 실패했을때 보내지는 에러 객체
    • info: 사용된 전송 매커니즘에 따른 정확한 포맷의 결과를 포함한다
      • info.messageId
      • info.envelope
      • info.accepted
      • info.rejected
      • info.pending
      • response
  • 메시지가 여러명의 수신자에게 전송되는 경우, 한 명의 수신자에게만 성공적으로 전달되어도 전송된 것으로 간주된다.
  • callback 인자가 전달되지 않으면, sendMail 메소드는 프로미스 객체를 리턴시킨다. Nodemailer는 내부적으로 프로미스를 사용하지 않지만, 편의를 위해 반환을 Promise로 래핑한다.
"use strict";
const nodemailer = require("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);

reference

profile
어제보다 나은 오늘을 만드는 중

0개의 댓글