首頁  >  文章  >  web前端  >  掌握 Node.js 中的電子郵件發送:逐步指南

掌握 Node.js 中的電子郵件發送:逐步指南

王林
王林原創
2024-08-28 06:11:02252瀏覽

Mastering Email Sending in Node.js: A Step-by-Step Guide

發送電子郵件是許多 Web 應用程式中的常見功能,無論是用於使用者註冊、密碼重設或行銷活動。在本指南中,我們將向您展示如何在 NodeMailer 模組的幫助下使用 Node.js 發送電子郵件。我們將涵蓋從設定項目到發送 HTML 電子郵件和處理附件的所有內容。


1.開始使用您的 Node.js 電子郵件專案

首先,您需要設定一個新的 Node.js 專案來發送電子郵件。

  • 建立專案資料夾
  mkdir emailtest
  cd emailtest
  • 初始化您的專案 建立包含以下內容的 package.json 檔案:
  {
    "name": "emailtest",
    "version": "1.0.0",
    "main": "index.js",
    "dependencies": {
      "nodemailer": "^6.0.0"
    }
  }
  • 安裝 NodeMailer 透過執行以下命令安裝所需的 NodeMailer 模組:
  npm install

2.發送您的第一封電子郵件

現在您的專案已設定完畢,讓我們發送一封簡單的電子郵件。

  • 建立一個index.js檔 新增以下程式碼以發送電子郵件:
  import nodemailer from 'nodemailer';

  const transporter = nodemailer.createTransport({
    host: 'smtp.freesmtpservers.com',
    port: 25
  });

  const mailOptions = {
    from: '"Test Email" <test@email.com>',
    to: 'someone@example.com',
    subject: 'Hello!',
    text: 'Hello world!',
    html: '<p>Hello world!</p>'
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log('Error:', error);
    } else {
      console.log('Email sent:', info.response);
    }
  });
  • 運行您的程式碼 使用 Node.js 運行程式碼:
  node index.js

您應該會看到電子郵件已發送的確認訊息。


3.新增附件到您的電子郵件

如果您需要透過電子郵件傳送文件,NodeMailer 讓這一切變得簡單。

  • 附附件的範例
  const mailOptions = {
    from: '"Test Email" <test@email.com>',
    to: 'someone@example.com',
    subject: 'Hello with Attachments!',
    text: 'Please find the attached files.',
    attachments: [
      {
        filename: 'test.txt',
        path: './test.txt' // Local file
      },
      {
        filename: 'example.txt',
        content: 'This is a text file content.' // Content as string
      }
    ]
  };

4.發送 HTML 電子郵件

HTML 電子郵件可以透過格式、圖片和連結使您的郵件更具吸引力。

  • HTML 電子郵件範例
  const mailOptions = {
    from: '"Test Email" <test@email.com>',
    to: 'someone@example.com',
    subject: 'Hello, HTML!',
    html: '<h1>Hello world!</h1><p>This is an HTML email.</p>'
  };

5.處理錯誤

處理錯誤以確保您的應用程式順利運行非常重要。

  • 錯誤處理範例
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log('Error:', error.message);
    } else {
      console.log('Email sent:', info.response);
    }
  });

結論

使用 Node.js 和 NodeMailer 發送電子郵件非常簡單。只需幾行程式碼,您就可以發送純文字或 HTML 電子郵件、附加文件並高效處理錯誤。隨著您需求的成長,您可以探索更進階的功能,例如與專用電子郵件服務整合和管理非同步電子郵件佇列。

以上是掌握 Node.js 中的電子郵件發送:逐步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn