본문 바로가기
개발/Node JS

Node JS - nodemailer로 구글, 네이버, 다음 카카오 메일 보내기 (Send Emails using nodemailer to Google, Naver, Daum Kakao)

by 피로물든딸기 2023. 12. 9.
반응형

Node JS 전체 링크

 

참고

- https://nodemailer.com/about/

- Toast UI Editor로 메일 보내기 with nodemailer

 

nodemailer를 이용해 구글(지메일), 네이버, 다음 메일을 보내보자.

npm install nodemailer

 

nodemailer 사용 방법 예시는 아래와 같다.

const nodemailer = require("nodemailer");

const sendEmail = async () => {
  const transporter = nodemailer.createTransport({
    service: "daum",
    host: "smtp.daum.net", // 사용할 이메일 서비스의 호스트 주소
    port: 465, // 이메일 서비스의 포트 번호 (25, 587, 465, 2525 등)
    //secure: true, // use TLS
    auth: { user: "DAUM ID", pass: "DAUM PASSWORD" },
  });

  const mailOptions = {
    from: "id1@hanmail.net", // from 설정 (naver, daum)
    to: "id2@hanmail.net", // a@hanmail.net, b@hanmail.net : , 로 구분
    cc: "id3@naver.com", // 참조
    bcc: "id4@gmail.com", // 비밀 참조
    subject: "메일 제목", // 제목
    // text : ""
    html: `<h1>내용</h1><p>메일 테스트</p>`,
    attachments: [
      {
        filename: "text1.txt",
        content: "hello world!",
      },
      {
        filename: 'text2.txt',
        path: "D:\\github\\node-server\\macro\\text2.txt"
      },
    ],
  };
  
  await transporter.sendMail(mailOptions);
};

sendEmail();

 

service, host를 설정하고 필요한 경우 port 번호도 지정해야 한다.

그리고 auth, pass에 ID와 비밀번호를 설정한다.

 

네이버와 다음의 경우 from을 설정하고, google의 경우 생략하면 auth에 설정한 ID로 메일을 전송한다.

 

그리고 to / cc / bcc수신자 / 참조 / 비밀참조를 설정할 수 있다.

다수에게 메일을 보내고 싶다면, 메일 주소를 "," 로 구분하면 된다.

 

subject는 메일 제목이고, text 또는 html을 이용하여 메일 내용을 보낸다. 

html 태그로 메일 양식을 설정하려면 html으로 설정해서 위와 같이 태그를 추가해야 한다.

 

attachments로 첨부 파일을 추가할 수 있다.

위의 경우 첨부 파일에는 text1.txt를 임시로 만들고 내용을 추가하였고

실제 노드 서버 경로에 존재하는 text2.txt를 첨부하였다.

 

첨부 파일에 대한 자세한 설명은 링크를 참고하자.

 

위와 같이 설정하면 아래와 같은 메일을 받을 수 있다.

Google

 

Naver

 

Daum


구글 지메일 (Google Gmail)

 

크롬에서 gmail 계정 로그인 후, 프로필을 클릭하고 Google 계정 관리 버튼을 누르자.

 

보안 탭에서 아래로 내려가 2단계 인증을 클릭하자.

 

더 아래로 내려가 앱 비밀번호 탭을 누르자.

 

App name을 설정한 후에 만들기 버튼을 클릭하자.

 

앱 비밀번호가 나오게 된다.

 

참고로 앱 비밀번호가 없다면 메일을 보냈을 때 아래와 같은 인증 에러가 발생할 수 있다.

Error: Invalid login: 535-5.7.8 Username and Password not accepted. For more information, go to
smtp-connection\index.js:969:20)
    at SMTPConnection._onData (D:\github\node-server\node_modules\nodemailer\lib\smtp-connection\index.js:755:14)
    at TLSSocket.SMTPConnection._onSocketData (D:\github\node-server\node_modules\nodemailer\lib\smtp-connection\index.js:193:44)
    at TLSSocket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at TLSSocket.Readable.push (node:internal/streams/readable:228:10) {
  code: 'EAUTH',
  response: '535-5.7.8 Username and Password not accepted. For more information, go to\n' +
    '535 5.7.8  https://support.google.com/mail/?p=BadCredentials s16-20020a170902989000b001cfc35d1326sm3142991plp.177 - gsmtp',
  responseCode: 535,
  command: 'AUTH PLAIN'
}

 

위의 비밀번호를 pass에 설정하면 된다.

gmail의 경우 별도 hostport를 설정하지 않아도 되고, from을 생략해도 된다.

const nodemailer = require("nodemailer");

const sendEmail = async () => {
  const transporter = nodemailer.createTransport({
    service: "gmail",
    //secure: true, // use TLS
    auth: { user: "GMAIL ID", pass: "GMAIL PASSWORD" },
  });

  const mailOptions = {
    // from: google 생략 가능
    to: "id2@hanmail.net", // a@hanmail.net, b@hanmail.net : , 로 구분
    cc: "id3@naver.com", // 참조
    bcc: "id4@gmail.com", // 비밀 참조
    subject: "메일 제목", // 제목
    // text : ""
    html: `<h1>내용</h1><p>메일 테스트</p>`,
    attachments: [
      {
        filename: "text1.txt",
        content: "hello world!",
      },
      {
        filename: 'text2.txt',
        path: "D:\\github\\node-server\\macro\\text2.txt"
      },
    ],
  };
  
  await transporter.sendMail(mailOptions);
};

sendEmail();

네이버 (Naver)

 

네이버 메일에 로그인한 후, 환경설정을 누른 후, POP3/SMTP 사용사용함으로 설정한다.

 

네이버 메일을 사용하기 위한 host와 port는 정해져 있다.

 

예시 코드는 다음과 같다. (service, host, port, auth 설정 + from 설정)

네이버의 경우 from을 설정해야 정상적으로 메일이 전송된다.

const nodemailer = require("nodemailer");

const sendEmail = async () => {
  const transporter = nodemailer.createTransport({
    service: "naver",
    host: "smtp.naver.com", // 사용할 이메일 서비스의 호스트 주소
    port: 465, // 이메일 서비스의 포트 번호 (25, 587, 465, 2525 등)
    //secure: true, // use TLS
    auth: { user: "NAVER ID", pass: "NAVER PASSWORD" },
  });

  const mailOptions = {
    from: "id1@naver.com", // from 설정 (naver, daum)
    to: "id2@hanmail.net", // a@hanmail.net, b@hanmail.net : , 로 구분
    cc: "id3@naver.com", // 참조
    bcc: "id4@gmail.com", // 비밀 참조
    subject: "메일 제목", // 제목
    // text : ""
    html: `<h1>내용</h1><p>메일 테스트</p>`,
    attachments: [
      {
        filename: "text1.txt",
        content: "hello world!",
      },
      {
        filename: 'text2.txt',
        path: "D:\\github\\node-server\\macro\\text2.txt"
      },
    ],
  };
  
  await transporter.sendMail(mailOptions);
};

sendEmail();

다음 카카오 (Daum Kakao)

 

다음 메일에 로그인한 후, 설정을 누르고 IMAP/POP3에서 POP3를 선택한 후, 사용함을 선택하자.

네이버와 마찬가지로 hostport가 정해져 있다.

 

다음의 경우도 from을 설정해야 정상적으로 메일이 전송된다. (service, host, port, auth 설정 + from 설정)

const nodemailer = require("nodemailer");

const sendEmail = async () => {
  const transporter = nodemailer.createTransport({
    service: "daum",
    host: "smtp.daum.net", // 사용할 이메일 서비스의 호스트 주소
    port: 465, // 이메일 서비스의 포트 번호 (25, 587, 465, 2525 등)
    //secure: true, // use TLS
    auth: { user: "DAUM ID", pass: "DAUM PASSWORD" },
  });

  const mailOptions = {
    from: "id1@hanmail.net", // from 설정 (naver, daum)
    to: "id2@hanmail.net", // a@hanmail.net, b@hanmail.net : , 로 구분
    cc: "id3@naver.com", // 참조
    bcc: "id4@gmail.com", // 비밀 참조
    subject: "메일 제목", // 제목
    // text : ""
    html: `<h1>내용</h1><p>메일 테스트</p>`,
    attachments: [
      {
        filename: "text1.txt",
        content: "hello world!",
      },
      {
        filename: 'text2.txt',
        path: "D:\\github\\node-server\\macro\\text2.txt"
      },
    ],
  };
  
  await transporter.sendMail(mailOptions);
};

sendEmail();
반응형