
使用這些基本 REST API 最佳實踐構建出色的 API
Node.js 是一個功能強大的 JavaScript 運行環境,以其無阻塞、事件驅動的架構和出色的異步操作能力(包括電子郵件處理)而著稱。
它能夠同時處理多個電子郵件請求而不影響性能,這使得 Node.js 成為將事務性電子郵件傳送集成到 Web 應用程序中的理想選擇。此解決方案易于擴展,即使面對大量電子郵件流量也能應對自如。
在本文中,您將學習如何在 Node.js 后端使用電子郵件 API 和 SMTP(簡單郵件傳輸協議)來發送電子郵件。我們將提供代碼示例,并探討這兩種方法的優缺點。此外,我們還將分享一些最佳實踐,以確保您的 Node.js 實施既可靠又安全。
選擇Email API還是將 Nodemailer 與 SMTP 服務器一起使用,很大程度上取決于您的設置所需的特性和功能,以及您的技術能力。
如果您希望利用電子郵件模板、分析功能、抑制管理、入站路由等高級特性,那么Email API 無疑是更好的選擇。而如果您更愿意自行配置和管理 SMTP 服務器(并且您有時間這樣做),或者您需要一個更簡潔的電子郵件發送解決方案,那么 Nodemailer 可能是您的最佳選擇。
以下是對兩者進行比較的快速概述。
特征 | Email API | Nodemailer |
易用性 | 易于實施,但需要技術知識 | 易于實施,但需要一些技術知識。如果使用自己的 SMTP 服務器,則需要相當多的配置。 |
可靠性 | 非常好的第三方服務可確保高送達率并處理重試 | 如果使用第三方服務,則非常好,如果使用自己的 SMTP 服務器設置,則可能難以管理 |
可擴展性 | 旨在無縫處理大量電子郵件 | 各不相同,如果使用第三方服務,通常非常好,否則,它取決于 SMTP 服務器的能力 |
成本 | 變量和基于使用情況 | 如果管理自己的 SMTP 服務器,則為低到中,如果使用第三方服務,則為可變和基于使用情況 |
特征 | 分析、模板和列表管理等高級功能 | 專注于發送沒有高級功能的電子郵件 |
安全 | 內置對 DKIM、SPF 和 DMARC 等安全協議的支持 | 安全性取決于 SMTP 服務器配置,如果使用第三方服務,則通常很好 |
屬地 | 依賴第三方服務的正常運行時間和性能 | 依賴第三方服務的正常運行時間和性能,如果管理自己的服務器,則依賴更多控制 |
定制 | 取決于 API 提供商的功能和限制 | 取決于 SMTP 服務提供商的功能和限制。如果管理自己的服務器,可以提供完全控制 |
設置復雜性 | 與提供的 SDK 和 API 輕松集成 | 與 SMTP 提供商的憑據簡單集成,自我管理的 SMTP 服務器需要對 SMTP 設置進行更多設置和配置 |
社區支持 | 來自 API 提供商的大型社區和廣泛的文檔 | 廣泛使用,提供廣泛的文檔和社區支持 |
無論您選擇使用 Email API 還是 Nodemailer,都需要先熟悉 Node.js 以及一些基礎編碼。本教程將介紹如何使用 MailerSend email API 和 SMTP 服務來發送電子郵件,因此您需要先注冊一個 MailerSend 帳戶。
以下是快速執行此操作的方法:
1. 注冊一個 MailerSend 帳戶。該服務是免費加入的,您將獲得 100 封免費電子郵件以及一個試用域,讓您能夠迅速開始設置。如果您對服務滿意,還可以訂閱 Free 計劃,每月最多可發送 3,000 封電子郵件,且無需支付任何費用。
2.注冊并驗證您的電子郵件地址后,接下來需要創建一個 API 令牌(如果您計劃使用電子郵件 API)或 SMTP 用戶和憑證(如果您計劃使用 Nodemailer 和 SMTP)。
要創建 API 令牌:
在控制面板中,單擊左側菜單中的 Integrations,然后單擊 API 令牌旁邊的 Manage。
在 API 令牌頁面上,單擊 Generate new token(生成新令牌),將出現一個用于創建令牌的彈出窗口。輸入可識別的名稱,選擇要為其創建令牌的域,并允許適當的訪問權限。然后單擊 Create token(創建令牌)。
將生成您的 API 令牌。復制并保存或下載令牌。關閉此彈出窗口后,出于安全原因,您將無法再次查看此令牌。
要創建新的 SMTP 用戶和憑證:
在控制面板中,單擊 Domains (域) 中的左側菜單。如果您想使用自己的域,可以通過單擊 Add domain (添加域) 來添加一個域,也可以使用試用域。
在要使用的域旁邊,單擊 Manage(管理)。向下滾動到 SMTP 部分,然后單擊 Generate new user(生成新用戶)。將出現一個彈出窗口,為您的新 SMTP 用戶輸入一個可識別的名稱,然后單擊 Save user(保存用戶)。
然后,您將獲得 SMTP 憑據,其中包括用戶名、密碼、服務器地址和端口。單擊 Save user(保存用戶)。然后,您可以將憑證保存在某個位置,或稍后通過單擊 Manage (管理) 來訪問它們。
現在,讓我們轉向在 Node.js 中使用電子郵件 API 發送電子郵件。使用 Email API 是發送電子郵件的強大且功能豐富的方式。盡管與 SMTP 一起使用某個軟件包仍需要一些技術知識,但使用 Email API 可以獲得更高級的功能和特性,這是值得的。
使用 MailerSend 的 API,您將獲得個性化、動態電子郵件模板、黑名單管理、分析、使用 SPF、DKIM 和 DMARC 安全協議的發件人身份驗證等功能。
如何開始使用:
1. 通過在系統上安裝 Node.js,確保您已準備好 Node.js 環境。
然后,在項目目錄中運行“npm init”命令,并按照提示設置 package.json 文件,以創建一個新的 Node.js 項目。
2. 接下來,使用以下命令安裝 MailerSend 包:
npm install mailersend
要在代碼中使用 env 變量,請安裝 Dotenv 模塊:
npm install dotenv --save
在以下代碼示例中,我們將對 API 令牌使用此方法。要為您的 API 令牌定義變量,請在 Node.js 項目的根目錄中創建一個名為 .env 的 .env 文件,并將 MAILERSEND_API_TOKEN 變量添加到該文件中。該文件應如下所示:
API_KEY=Your_API_Key_Here
讓我們看一下使用 MailerSend API 發送帶有 Node.js 的簡單 HTML 電子郵件所需的代碼。在此示例中,我們將發送一封試用注冊確認電子郵件,以確認用戶的試用訂閱,并向他們提供任何相關信息。
import 'dotenv/config';
import {
MailerSend,
EmailParams,
Sender,
Recipient
} from "mailersend";
const mailerSend = new MailerSend({
apiKey: process.env.API_KEY,
});
const sentFrom = new Sender("bob@yourbusiness.com", "Bob");
const recipients = [
new Recipient("pam@theoffice.com", "Pam")
];
const htmlContent = `
<p>Hey there!</p>
<p>Welcome to Your Business, we're happy to have you here!</p>
<p>You'll be happy to know that your free trial awaits, all you need to do is head to your account, log in and start playing.</p>
<p>Remember to check out our guides and contact support if you need anything.</p>
<br>
<p>Regards,</p>
<p>The Your Business Team</p>
`;
const emailParams = new EmailParams()
.setFrom(sentFrom)
.setTo(recipients)
.setReplyTo(sentFrom)
.setSubject("Welcome! Your free trial is ready.")
.setHtml(htmlContent)
.setText("Hey there! Welcome to Your Business, we're happy to have you here! You'll be happy to know that your free trial awaits, all you need to do is head to your account, log in and start playing. Remember to check out our guides and contact support if you need anything. Regards, The Your Business Team");
mailerSend.email.send(emailParams)
.then(response => {
console.log("Email sent successfully:", response);
})
.catch(error => {
console.error("Error sending email:", error);
})
如果需要添加任何 CC 或 BCC 收件人,則需要修改 emailParams 對象以包含這些收件人。以下是添加的 CC 和 BCC 收件人的代碼:
import 'dotenv/config';
import {
MailerSend,
EmailParams,
Sender,
Recipient
} from "mailersend";
const mailerSend = new MailerSend({
apiKey: process.env.API_KEY,
});
const sentFrom = new Sender("bob@yourbusiness.com", "Bob");
const recipients = [
new Recipient("pam@theoffice.com", "Pam")
];
const ccRecipients = [
new Recipient("john@yourbusiness.com", "John")
];
const bccRecipients = [
new Recipient("sales@yourbusiness.com", "Sales")
];
const htmlContent = `
<p>Hey there!</p>
<p>Welcome to Your Business, we're happy to have you here!</p>
<p>You'll be happy to know that your free trial awaits, all you need to do is head to your account, log in and start playing.</p>
<p>Remember to check out our guides and contact support if you need anything.</p>
<br>
<p>Regards,</p>
<p>The Your Business Team</p>
`;
const emailParams = new EmailParams()
.setFrom(sentFrom)
.setTo(recipients)
.setCc(ccRecipients) // Adding CC recipients
.setBcc(bccRecipients) // Adding BCC recipients
.setReplyTo(sentFrom)
.setSubject("Welcome! Your free trial is ready.")
.setHtml(htmlContent)
.setText("Hey there! Welcome to Your Business, we're happy to have you here! You'll be happy to know that your free trial awaits, all you need to do is head to your account, log in and start playing. Remember to check out our guides and contact support if you need anything. Regards, The Your Business Team");
mailerSend.email.send(emailParams)
.then(response => {
console.log("Email sent successfully:", response);
})
.catch(error => {
console.error("Error sending email:", error);
})
使用電子郵件API的一個主要優勢在于能夠輕松發送專業設計的電子郵件模板。在MailerSend平臺上,通過模板構建器,您可以非常便捷地創建模板——無論是使用拖放編輯器、富文本編輯器,還是直接從HTML編輯器開始構建。之后,您只需獲取模板的ID,并將其整合到您的代碼中即可。
以下是我們使用模板時免費試用電子郵件的代碼:
import 'dotenv/config';
import {
MailerSend,
EmailParams,
Sender,
Recipient
} from "mailersend";
const mailerSend = new MailerSend({
apiKey: process.env.API_KEY,
});
const sentFrom = new Sender("bob@yourbusiness.com", "Bob");
const recipients = [
new Recipient("pam@theoffice.com", "Pam")
];
const emailParams = new EmailParams()
.setFrom(sentFrom)
.setTo(recipients)
.setReplyTo(sentFrom)
.setSubject("Welcome! Your free trial is ready.")
.setTemplateId('templateId');
mailerSend.email.send(emailParams)
.then(response => {
console.log("Email sent successfully:", response);
})
.catch(error => {
console.error("Error sending email:", error);
})
個性化變量能夠幫助您根據導入的數據(例如收件人的姓名)為不同的收件人定制電子郵件內容。在使用 MailerSend 時,您可以通過 {{var}} 的格式來定義變量,并將它們嵌入到電子郵件內容中。
以下是一個示例代碼,展示了如何發送一封包含個性化內容的電子郵件,通知用戶他們的試用期即將結束。
import 'dotenv/config';
import {
MailerSend,
EmailParams,
Sender,
Recipient
} from "mailersend";
const mailerSend = new MailerSend({
apiKey: process.env.API_KEY,
});
const sentFrom = new Sender("bob@youbusiness.com", "Bob");
const recipients = [
new Recipient("pam@theoffice.com", "Pam")
];
const personalization = [{
email: "pam@theoffice.com",
data: {
name: 'Pam'
},
}];
const htmlContent = `
<p>Hi {{name}}.</p>
<p>We wanted to remind you that your free trial will expire in 3 days.</p>
<p>If you like what you see and would like to continue using Your Business, you can purchase a Premium plan by clicking Upgrade in your dashboard.</p>
<p>If you choose not to upgrade, you’ll lose access to premium features and your data, which will be permanently deleted after 30 days.</p>
<br>
<p>Regards,</p>
<p>The Your Business Team</p> `;
const emailParams = new EmailParams()
.setFrom(sentFrom)
.setTo(recipients)
.setReplyTo(sentFrom)
.setPersonalization(personalization)
.setSubject("{{name}}, your free trial is about to expire.")
.setHtml(htmlContent)
.setText("Hi {{name}}. We wanted to remind you that your free trial will expire in 3 days. If you like what you see and would like to continue using Your Business, you can purchase a Premium plan by clicking Upgrade in your dashboard. If you choose not to upgrade, you’ll lose access to premium features and your data, which will be permanently deleted after 30 days. Regards, The Your Business Team");
mailerSend.email.send(emailParams)
.then(response => {
console.log("Email sent successfully:", response);
})
.catch(error => {
console.error("Error sending email:", error);
})
當Pam決定購買訂閱時,就到了發送她第一張發票的時候。為了發送帶有附件的電子郵件,我們將使用attachment類,并通過設置content、filename和type屬性來定義該附件。
import 'dotenv/config';
import {
MailerSend,
EmailParams,
Sender,
Recipient
} from "mailersend";
const mailerSend = new MailerSend({
apiKey: process.env.API_KEY,
});
const sentFrom = new Sender("bob@youbusiness.com", "Bob");
const recipients = [
new Recipient("pam@theoffice.com", "Pam")
];
const attachmentContent = fs.readFileSync('/path/to/invoice.pdf', {
encoding: 'base64'
});
const attachment = new Attachment({
content: attachmentContent,
filename: 'invoice.pdf',
type: 'application/pdf',
disposition: 'attachment' // Optional: Specifies that it's an attachment
});
]
const personalization = [{
email: "pam@theoffice.com",
data: {
name: 'Pam'
},
}];
const htmlContent = `
<p>Hi {{name}}.</p>
<p>Thanks for using Your Business!</p>
<p>Your subscription has been renewed for 1 month. The details of your invoice are below and a downloadable copy has been attached</p>
<br>
<p>Regards,</p>
<p>The Your Business Team</p> `;
const emailParams = new EmailParams()
.setFrom(sentFrom)
.setTo(recipients)
.setReplyTo(sentFrom)
.setPersonalization(personalization)
.setSubject("{{name}}, here’s your Your Business invoice.")
.setHtml(htmlContent)
.setText("Hi {{name}}. Thanks for using Your Business! Your subscription has been renewed for 1 month. The details of your invoice are below and a downloadable copy has been attached Regards, The Your Business Team");
// Assign the attachment to emailParams
emailParams.attachments = [attachment];
mailerSend.email.send(emailParams)
.then(response => {
console.log("Email sent successfully:", response);
})
.catch(error => {
console.error("Error sending email:", error);
})
MailerSend提供的批量電子郵件功能,能夠通過一個單一的API調用,方便地實現個性化電子郵件的批量發送。這一功能幫助您規避了速率限制,并顯著提升了發送效率。
在此示例中,我們計劃向Pam和Dwight發送反饋請求。此類交易性電子郵件非常適合進行批量發送,因為其對時間的要求并不嚴格,可以隨時進行。
import 'dotenv/config';
import {
MailerSend,
EmailParams,
Sender,
Recipient
} from "mailersend";
const mailerSend = new MailerSend({
apiKey: process.env.API_KEY,
});
const sentFrom = new Sender("bob@yourbusiness.com", "Bob");
const bulkEmails = [];
const personalization = [{
email: "pam@theoffice.com",
data: {
name: 'Pam'
},
},
{
email: "dwight@theoffice.com",
data: {
name: 'Dwight'
},
}
];
const htmlContent = `
<p>Hi {{name}}.</p>
<p>Thanks for using Your Business!</p>
<p>As you’ve been using the app for a while now, we’d love to hear your thoughts.</p>
<p>Our customer feedback survey takes just a few minutes to complete and will help us to make our offering even better.</p>
<p><a href="url to your survey" target="_blank">Take survey</a></p>
<p>Thanks for your participation!</p>
<br>
<p>Regards,</p>
<p>The Your Business Team</p>`;
const textContent = `
Hi {{name}}.
Thanks for using Your Business!
As you’ve been using the app for a while now, we’d love to hear your thoughts.
Our customer feedback survey takes just a few minutes to complete and will help us to make our offering even better.
Take survey: url to your survey
Thanks for your participation!
Regards,
The Your Business Team`;
const emailParams1 = new EmailParams()
.setFrom(sentFrom)
.setTo([new Recipient("pam@theoffice.com", "Pam")])
.setSubject("Let us know what you think.")
.setHtml(htmlContent)
.setText(textContent)
.setPersonalization([personalization[0]]);
bulkEmails.push(emailParams1);
const emailParams2 = new EmailParams()
.setFrom(sentFrom)
.setTo([new Recipient("dwight@theoffice.com", "Dwight")])
.setSubject("Let us know what you think.")
.setHtml(htmlContent)
.setText(textContent)
.setPersonalization([personalization[1]]);
bulkEmails.push(emailParams2);
mailerSend.email.send(emailParams)
.then(response => {
console.log("Email sent successfully:", response);
})
.catch(error => {
console.error("Error sending email:", error);
})
如果您需要在特定時間或日期發送電子郵件,則可以使用 .setSendAt 參數和 Unix 時間戳來安排它。以下是我們發送給 Pam 和 Dwight 的維護通知電子郵件的代碼示例。
import 'dotenv/config';
import {
MailerSend,
EmailParams,
Sender,
Recipient
} from "mailersend";
const mailerSend = new MailerSend({
apiKey: process.env.API_KEY,
});
const sentFrom = new Sender("bob@yourbusiness.com", "Bob");
const recipients = [
new Recipient("pam@theoffice.com", "Pam"),
new Recipient("Dwight@theoffice.com", "Dwight")
];
const htmlContent = `
<p>We would like to inform you that the Your Business app is scheduled for maintenance on Tuesday, 25th June 2024 at 3 AM.</p>
<p>This will result in some downtime between the hours of 3 AM and 3:30 AM, after which services will resume as usual.</p>
<p>If you have any questions, please contact support.</p>
<br>
<p>Regards,</p>
<p>The Your Business Team</p>`;
const textContent = `
We would like to inform you that the Your Business app is scheduled for maintenance on Tuesday, 25th June 2024 at 3 AM.
This will result in some downtime between the hours of 3 AM and 3:30 AM, after which services will resume as usual.
If you have any questions, please contact support.
Regards,
The Your Business Team
const emailParams = new EmailParams()
.setFrom(sentFrom)
.setTo(recipients)
.setReplyTo(sentFrom)
.setSubject("Notice of scheduled maintenance on Tuesday, 25th June")
.setHtml(htmlContent)
.setText(textContent)
.setSendAt(Math.floor((new Date(Date.now()+ 30*60*1000)).getTime() / 1000)); //send in 30mins NB:param has to be a Unix timestamp e.g 2443651141
mailerSend.email.send(emailParams)
.then(response => {
console.log("Email sent successfully:", response);
})
.catch(error => {
console.error("Error sending email:", error);
})
在此示例中,Date.now()
方法用于獲取當前時間(以毫秒為單位)。接著,通過向當前時間添加 30 * 60 * 1000
毫秒,計算出從當前時刻起30分鐘后的時間點。
Date
對象的 getTime()
方法返回自 Unix 紀元以來的毫秒數。為了將其轉換為以秒為單位的 Unix 時間戳,我們將毫秒數除以 1000
。
Math.floor()
?函數用于將得到的時間戳向下舍入到最接近的整數,因為 Unix 時間戳必須是整數。最后,使用?EmailParams
?的?setSendAt
?方法來設置計劃發送時間,而該時間是通過前面計算出的 Unix 時間戳來確定的。
如果您想使用 SMTP,Nodemailer 無疑是一個很好的解決方案。Node.js 模塊允許您以簡單有效的方式將電子郵件發送集成到 Node.js 應用程序中,同時支持身份驗證機制以確保與 SMTP 服務器的連接安全。
簡而言之:
注意:
雖然您可以直接使用 SMTP 服務器在 Node.js 中發送電子郵件,但這種方法缺少了像 Nodemailer 這樣的庫所能提供的豐富安全功能,可能會使您的應用程序面臨網絡攻擊和數據泄露的風險。
所以讓我們開始吧。
1. 首先,請確保您的系統上已經安裝了 Node.js,這是進行后續操作的基礎。
然后,在您的項目目錄中運行 npm init 命令,并根據提示完成 package.json 文件的設置,從而創建一個新的 Node.js 項目。
2. 安裝 Nodemailer 模塊:
npm install nodemailer
3. 在項目根目錄中為您的 MailerSend SMTP 憑證創建一個 .env 文件 — 如果您需要復習如何創建 SMTP 用戶和檢索憑證,請跳回本節的開頭或閱讀我們的指南如何使用 SMTP 發送電子郵件。
您需要添加 SMTP 服務器地址、端口、用戶名和密碼:
SMTP_HOST=smtp.mailersend.net
SMTP_PORT=587
SMTP_USER=your_mailersend_username
SMTP_PASS=your_mailersend_password
4. 安裝 dotenv 包以從 .env 文件加載 SMTP 憑證:
npm install dotenv
5. 發送電子郵件!以下是使用我們的試用確認電子郵件的代碼示例:
import 'dotenv/config';
import nodemailer from 'nodemailer';
// Load environment variables from .env file
import dotenv from 'dotenv';
dotenv.config();
// Create a transporter object using SMTP transport
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false, // true for 465, false for other ports
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
// Setup email data
const mailOptions = {
from: '"Bob" <bob@yourbusiness.com>', // sender address
to: 'pam@theoffice.com', // list of receivers
subject: 'Welcome! Your free trial is ready.', // Subject line
text: 'Hey there! Welcome to Your Business, we\'re happy to have you here! You\'ll be happy to know that your free trial awaits, all you need to do is head to your account, log in and start playing. Remember to check out our guides and contact support if you need anything. Regards, The Your Business Team', // plain text body
html: `
<p>Hey there!</p>
<p>Welcome to Your Business, we're happy to have you here!</p>
<p>You'll be happy to know that your free trial awaits, all you need to do is head to your account, log in and start playing.</p>
<p>Remember to check out our guides and contact support if you need anything.</p>
<br>
<p>Regards,</p>
<p>The Your Business Team</p>
`, // html body
};
// Send email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
});
就是這樣!
如果你想在電子郵件中添加附件,你只需要在 mailOptions 中包含一個 attachments 數組:
attachments: [
{
filename: 'invoice.pdf',
path: '/path/to/invoice.pdf',
},
]
還可以通過修改電子郵件內容并定義收件人的個性化數據,在電子郵件中包含個性化。這是該反饋請求,其中為收件人的姓名設置了個性化變量:
import 'dotenv/config';
import nodemailer from 'nodemailer';
import dotenv from 'dotenv';
dotenv.config();
// Create a transporter object using SMTP transport
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false, // true for 465, false for other ports
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
// Define your list of recipients and their personalization data
const recipients = [{
email: 'pam@theoffice.com',
name: 'Pam',
},
{
email: 'dwight@theoffice.com',
name: 'Dwight',
},
];
const sendPersonalizedEmails = async (recipients) => {
for (const recipient of recipients) {
// Personalize the email content
const textContent = Hi ${recipient.name},\nThanks for using Your Business! As you’ve been using the app for a while now, we’d love to hear your thoughts. Our customer feedback survey takes just a few minutes to complete and will help us to make our offering even better. Take survey: url to your survey\nThanks for your participation!\nRegards,\nThe Your Business Team
;
const htmlContent = `
<p>Hi ${recipient.name}.</p>
<p>Thanks for using Your Business!</p>
<p>As you’ve been using the app for a while now, we’d love to hear your thoughts.</p>
<p>Our customer feedback survey takes just a few minutes to complete and will help us to make our offering even better.</p>
<p><a href="url to your survey" target="_blank">Take survey</a></p>
<p>Thanks for your participation!</p>
<br>
<p>Regards,</p>
<p>The Your Business Team</p>
`;
const mailOptions = {
from: '"Bob" <bob@yourbusiness.com>', // sender address
to: recipient.email, // recipient address
subject: 'Let us know what you think.', // Subject line
text: textContent, // plain text body
html: htmlContent, // html body
};
// Send the email
try {
let info = await transporter.sendMail(mailOptions);
console.log('Message sent: %s', info.messageId);
} catch (error) {
console.error('Error sending email:', error);
}
}
};
sendPersonalizedEmails(recipients);
若操作得當并遵循最佳實踐,Node.js 將成為一種高效、可靠且安全的電子郵件發送方式。如果您已準備好開始使用,請牢記以下最佳實踐,以確保順利實施并提升電子郵件發送體驗。
盡管我們因Email API的靈活性和高級功能而對其青睞有加,但我們深知它并非適用于所有人。SMTP和電子郵件API在易用性、功能性、可靠性和安全性方面各有千秋。若您尋求一種簡潔且經濟高效的解決方案,SMTP可能是您的理想之選。然而,若您期望獲得更多功能、高級工作流程及跟蹤能力,那么API將是您的最佳選擇。
此外,管理自己的SMTP服務器要復雜得多,需要您自行實施安全措施以確保發送安全。與諸如MailerSend這樣的第三方提供商合作,則意味著送達率、安全性及其他所有問題都將得到妥善處理。
MailerSend的Email API和SMTP均構建于同一強大、安全且可靠的發送基礎設施之上,并提供對活動和分析的訪問權限。因此,無論您選擇使用我們的API還是保持簡單的SMTP方式,都可以放心,您的電子郵件將得到妥善處理。
為了集成電子郵件發送功能,您需要使用一些敏感數據,比如 API 密鑰和 SMTP 憑據。這些數據若直接暴露在代碼中,會帶來安全風險!通過將它們保存在?.env
?文件中,您可以在代碼中隱藏這些數據,從而避免泄露。此外,這也使得管理電子郵件發送變得更加便捷,因為您無需在每個電子郵件發送的腳本中硬編碼 API 密鑰或 SMTP 憑據,只需在?.env
?文件中更新相關數據即可。
為可能出現的故障做好準備是構建任何優秀系統的關鍵一環。在電子郵件發送的場景中,您需要確保應用程序能夠妥善處理任何錯誤,避免崩潰或出現意外的響應。為此,您可以使用 try-catch 塊或 promise 錯誤處理機制來捕獲并記錄任何錯誤。這樣做不僅能提升應用程序的可靠性,還能讓故障排除工作變得更加輕松。
速率限制涉及使用 Bottleneck 等軟件包來限制電子郵件發送。下面是一個示例:
import Bottleneck from 'bottleneck';
const limiter = new Bottleneck({
minTime: 100 / maxEmailsPerSecond,
});
limiter.schedule(() => transporter.sendMail(mailOptions));
這樣做可以防止你的應用壓垮你的電子郵件服務器,并避免你的電子郵件服務提供商設置的任何速率限制。
對電子郵件地址進行實時驗證,能夠優化您的收件人列表,使其保持高效且持久,進而幫助您維持較高的電子郵件送達率。盡管您可以通過 JavaScript 中的正則表達式來檢查電子郵件地址的格式是否正確,但這僅僅停留在表面層面。為了更深入地檢查不存在的郵箱、拼寫錯誤以及一次性電子郵件等問題,推薦使用電子郵件驗證服務。
您可以查閱相關文章,了解如何借助 MailerSend 開始進行實時電子郵件驗證。
電子郵件模板能夠助您發送符合品牌調性的專業設計郵件。同時,它們還簡化了電子郵件內容的管理流程,并有助于保持代碼的清晰與簡潔。您只需構建模板,并將其單獨存儲,隨后在發送電子郵件時將其加載即可。
在使用 MailerSend 時,這一過程尤為簡便。MailerSend 提供了三個電子郵件構建器選項,包括拖放、豐富文本以及 HTML。構建模板后,您只需檢索模板 ID,并將其添加到您的代碼中即可。
或許您會認為電子郵件分析僅僅是業務負責人關注的事項,用以查看電子郵件的轉化次數。但實際上,分析能夠為您提供關鍵的性能洞察,幫助您識別送達率方面存在的問題。
更重要的是,借助MailerSend,您可以輕松利用webhook設置通知,這樣一旦有任何異常情況發生,您就能實時了解,而無需親自查看分析儀表板。
利用 Email API 或 Nodemailer 是通過 Node.js 發送電子郵件的常用且明智之選,這背后有著充分的理由。當您選擇與可靠的電子郵件服務提供商合作時,幾乎可以確保不會出錯。而且,作為 JavaScript 運行時的一部分,這種方式是將電子郵件發送功能集成到 JavaScript 應用程序中的最為簡便的方法。
若您正在尋找一個既能保證卓越送達率又強大且安全的 Email API,那么 MailerSend 無疑是一個值得嘗試的選擇。
原文鏈接:https://www.mailersend.com/blog/send-email-nodejs