본문 바로가기
Knowledge/- Service

nodejs를 활용한 이메일 보내기 (Nodemailer)

by Yoojacha 2022. 8. 31.

npm install nodemailer


let transporter = nodemailer.createTransport(transport[, defaults])

 

  • transporter 는 이메일을 보낼 수 있는 객체로 만들어진다.
  • transport 는 transport 설정 객체, connection url 혹은 transport plugin 인스턴스이다.
  • defaults 는 메일 옵션을 위한 기본 값들이 있는 객체이다.

 

  • port 는 연결을 위한 것이다. (defaults to 587 if is secure is false or 465 if true)
  • host 는 연결을 위한 호스트이름 혹은 아이피 주소이다. (defaults to ‘localhost’)
  • auth – 인증 데이터를 정의하는 곳이다.
    • type 은 인증 타입을 결정한다. 기본값은 'login', 다른 옵션에는 'oauth2',  'custom' 이 있다.
    • user 는 유저의 이름이다.
    • pass 는 일반 로그인이 사용됐을 때 유저를 위해 비밀번호를 입력하는 것이다.
  • authMethod – defines preferred authentication method, defaults to ‘PLAIN’

Send using SMTP

See the details about setting up a SMTP based transporter here.

Send using a transport plugin

See the details about setting up a plugin based transporter here.


Sending mail

transporter.sendMail(data[, callback])

 

 

Message configuration :: Nodemailer

\ Message configuration The following are the possible fields of an email message: Common fields from - The email address of the sender. All email addresses can be plain ‘[email protected]’ or formatted '“Sender Name” [email protected]', see Addr

nodemailer.com

  • callback 은 옵션인 콜백 함수로, 한 번 전달된 메시지를 실행하거나 실패한 메시지를 실행한다.
    • err 은 메시지가 실패했을 때의 에러 객체이다.
    • info 는 result를 포함하고 있다. 사용된 transport 메커니즘에 따른 정확한 포맷을 가지고 있다.
      • info.messageId 대부분의 transport들은 이 속성과 함께 사용된 최종 Message-Id 값을 반환해야 한다.
      • info.envelope 은 메시지를 위한 봉투(envelope) 객체를 포함한다.
      • info.accepted SMTP 전송에서 반환되는 배열이다. (서버에서 수락한 수신자 주소 포함)
      • info.rejected SMTP 전송에서 반환되는 배열이다. (서버에 의해 거부된 수신자 주소 포함) 
      • info.pending 는 direct SMTP 전송에서 반환되는 배열이다.
        (서버 응답과 함께 일시적으로 거부된 수신자 주소를 포함)
      • response 는 SMTP 전송에서 반환되는 문자열이고, 서버의 마지막 SMTP 응답을 포함한다.

* 메시지에 여러 명의 수신인이 포함된 경우에 적어도 한 명의 수신인이 허락된 경우에 메시지는 발송된 것으로 간주된다


The following are the possible fields of an email message:

  • from
  • to
  • cc
  • bcc
  • subject
  • text
  • html
  • attachments
var message = {
  from: "sender@server.com",
  to: 'foobar@example.com, "Ноде Майлер" <bar@example.com>, "Name, User" <baz@example.com>',
  subject: "Message title",
  text: "Plaintext version of the message",
  html: "<p>HTML version of the message</p>"
};

그 외 다른 옵션들 : https://nodemailer.com/message/

 

Message configuration :: Nodemailer

\ Message configuration The following are the possible fields of an email message: Common fields from - The email address of the sender. All email addresses can be plain ‘[email protected]’ or formatted '“Sender Name” [email protected]', see Addr

nodemailer.com


ATTACHMENTS

attachments option in the message object that contains an array of attachment objects.

  • filename
  • content
  • path
  • href
  • httpHeaders
  • contentType
  • contentDisposition
  • cid
  • encoding
  • headers
  • raw

https://nodemailer.com/message/attachments/

 

Attachments :: Nodemailer

Attachments attachments option in the message object that contains an array of attachment objects. Attachment object consists of the following properties: filename - filename to be reported as the name of the attached file. Use of unicode is allowed. conte

nodemailer.com


보내는 주소, 이름을 적는 방법

https://nodemailer.com/message/addresses/

 

Address object :: Nodemailer

Address object All email addresses can be plain email addresses or with formatted name (includes unicode support) Notice that all address fields (even *from:*) are comma separated lists, so if you want to use a comma (or any other special symbol) in the na

nodemailer.com


CALENDAR EVENTS ( 나중에 필요할 때 업데이트)

 


Set EML file as message body

This example loads the entire message source from a file

let message = {
    envelope: {
        from: 'sender@example.com',
        to: ['recipient@example.com']
    },
    raw: {
        path: '/path/to/message.eml'
    }
};

example

"use strict";

const nodemailer = require("nodemailer");

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();

  // 기본 SMTP transport 를 활용하는 재사용가능한 transporter 객체를 생성
  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
    },
  });

  // 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>

  // Ethereal 계정을 통해서 보냈을 때만 미리보기가 가능하다. 
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

// 실행
main().catch(console.error);

예제 사용 유튜브 링크

https://www.youtube.com/watch?v=nF9g1825mwk 

 


SMTP 서버 이용하기 (gmail)

https://privatenote.tistory.com/172

 

구글 Gmail SMTP 설정 방법

Gmail 에서 아웃룩이나 다른 전자 메일 프로그램을 통해 메일을 보낼 수 있도록 하기 위해 Gmail SMTP(Simple Mail Transfer Protocol) 설정에 대해서 알려드리겠습니다. Gmail 기본 SMTP 설정 SMTP 서버 : smtp...

privatenote.tistory.com


 

댓글