본문 바로가기

nodejs

nodejs에서 이메일 보내기

728x90

Node.js에서 이메일 전송하는 방법입니다.

우선 nodemailer 라이브러리를 설치합니다.

npm을 사용하시면 아래를 복붙해주세요

npm install nodemailer

 

그 후 아래처럼 작성해줍니다.

const nodemailer = require('nodemailer');

// SMTP 설정
const transporter = nodemailer.createTransport({
  service: 'Gmail', // 이메일 서비스 제공자 (Gmail, Outlook, Yahoo 등)
  auth: {
    user: 'your_email@gmail.com', // 보내는 이메일 주소
    pass: 'your_password' // 보내는 이메일의 비밀번호 또는 애플리케이션 비밀번호 (안전한 앱 설정 필요)
  }
});

// 이메일 데이터
const mailOptions = {
  from: 'your_email@gmail.com', // 발신자 이메일 주소
  to: 'recipient_email@example.com', // 수신자 이메일 주소 (여러 개일 경우 배열로 전달 가능)
  subject: '테스트 이메일', // 이메일 제목
  text: '안녕하세요! 테스트 이메일이 발송되었습니다.' // 이메일 본문 (텍스트)
};

// 이메일 보내기
transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.error('이메일 전송 오류:', error);
  } else {
    console.log('이메일 전송 성공:', info.response);
  }
});

패스워드는 구글 비밀번호가 아니라 계정 설정 > 보안에서 앱 비밀번호를 만들어 줘야합니다.

https://myaccount.google.com/apppasswords

 

 

이렇게 만들 수 있습니다.

const nodemailer = require('nodemailer');

/** 이메일 발송 */
function getEmailSend(email_to, email_subject, email_content) {
    let email_from = '구글@gmail.com';
    let user_pass = '비밀번호';
    const transporter = nodemailer.createTransport({
        service: 'Gmail', // 이메일 서비스 제공자 (Gmail, Outlook, Yahoo 등)
        auth: {
            user: email_from, // 보내는 이메일 주소
            pass: user_pass // 보내는 이메일의 비밀번호 또는 애플리케이션 비밀번호 (안전한 앱 설정 필요)
        }
    });

    const mailOptions = {
        from: email_from, // 발신자 이메일 주소
        to: email_to, // 수신자 이메일 주소 (여러 개일 경우 배열로 전달 가능)
        subject: email_subject, // 이메일 제목
        html: email_content // 이메일 본문 (텍스트)
      };

      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          console.error('이메일 전송 오류:', error);
        } else {
          console.log('이메일 전송 성공:', info.response);
        }
      });
}

function getSignupForm(url, email) {
  let html = `<!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>회원가입 인증 메일</title>
      <style>
          /* 스타일링을 위한 CSS */
          body {
              font-family: Arial, sans-serif;
              background-color: #f5f5f5;
          }
  
          .container {
              max-width: 400px;
              margin: 0 auto;
              padding: 20px;
              background-color: #fff;
              border-radius: 5px;
              box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
          }
  
          table {
              width: 100%;
          }
  
          table tr td {
              padding: 10px;
          }
  
          .btn {
              display: inline-block;
              padding: 10px 20px;
              background-color: #007BFF;
              color: #fff;
              text-decoration: none;
              border-radius: 5px;
          }
      </style>
  </head>
  <body>
      <div class="container">
          <h2>회원가입 인증 메일</h2>
          <p>회원가입을 완료하려면 아래 버튼을 클릭하세요.</p>
          <table>
              <tr>
                  <td>이메일:</td>
                  <td>${email}</td>
              </tr>
              <tr>
                  <td>인증 링크:</td>
                  <td><a href="${url}">인증하기</a></td>
              </tr>
          </table>
          <p>인증 링크가 작동하지 않는 경우, 다음 링크를 복사하여 웹 브라우저에 붙여넣으세요:</p>
          <p>${url}</p>
          <p>감사합니다!</p>
          <a class="btn" href="${url}">인증하기</a>
      </div>
  </body>
  </html>
  `;
  return html;
}


function getSigninForm(url, email) {
    let html = `<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>로그인 인증 메일</title>
        <style>
            /* 스타일링을 위한 CSS */
            body {
                font-family: Arial, sans-serif;
                background-color: #f5f5f5;
            }
    
            .container {
                max-width: 400px;
                margin: 0 auto;
                padding: 20px;
                background-color: #fff;
                border-radius: 5px;
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            }
    
            table {
                width: 100%;
            }
    
            table tr td {
                padding: 10px;
            }
    
            .btn {
                display: inline-block;
                padding: 10px 20px;
                background-color: #007BFF;
                color: #fff;
                text-decoration: none;
                border-radius: 5px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h2>로그인 인증 메일</h2>
            <p>로그인하려면 아래 버튼을 클릭하세요.</p>
            <table>
                <tr>
                    <td>이메일:</td>
                    <td>${email}</td>
                </tr>
                <tr>
                    <td>인증 링크:</td>
                    <td><a href="${url}">인증하기</a></td>
                </tr>
            </table>
            <p>인증 링크가 작동하지 않는 경우, 다음 링크를 복사하여 웹 브라우저에 붙여넣으세요:</p>
            <p>${url}</p>
            <p>감사합니다!</p>
            <a class="btn" href="${url}">인증하기</a>
        </div>
    </body>
    </html>
    `;
    return html;
  }


module.exports = {
    getEmailSend, getSignupForm, getSigninForm
};

 

/** 유저 가입 이메일 보내기 */
router.post('/text_user_email', function(req, res, next) {
const xxx = modules_a.getRandom(20);
let randomString = modules_crypto.getEncryptUltra(xxx);
const urlrequrl = new URL(req.url, `http://${req.headers.host}`);
let url = urlrequrl.origin + '/user/signup/' + randomString;
let email_to = req.body.email;
let html = modules_email.getSignupForm(url, email_to);
let email_subject = '[회원 가입 인증] 회원님의 계정을 인증해주세요!';
let email_content = html;
modules_email.getEmailSend(email_to, email_subject, email_content);
try {
  req.session.signupKey = xxx;
  req.session.signupEmail = email_to;
  req.session.save(()=>{
    console.log('세션 데이터 설정됨');
  })
  console.log(req.session);
  
} catch (err) {
console.error('세션 오류:', err);
res.status(500).send('세션 오류');
}
});

 

<textarea class="textarea_short" id="text_user_email_signin" placeholder="Email을 입력하세요." spellcheck="false">이메일@naver.com</textarea>
<button class="btn" id="text_user_email_signin_btn">로그인 이메일 보내기</button>

 

// 로그인 이메일 전송
document.getElementById('text_user_email_signin_btn').addEventListener('click', () => {
    const tableEmail = document.getElementById('text_user_email_signin').value;
  fetch(url+'/user/text_user_email_signin', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ email: tableEmail })
  })
  .then(response => response.json())
  .then(data => {
    console.log(data);
    document.getElementById('text_user_email_singin').value = data;
  })
  .catch(error => {
    console.error('오류:', error);
  });
});
728x90