鍵.png)
使用這些基本 REST API 最佳實踐構(gòu)建出色的 API
Node.js 是一個功能強大的 JavaScript 運行環(huán)境,以其無阻塞、事件驅(qū)動的架構(gòu)和出色的異步操作能力(包括電子郵件處理)而著稱。
它能夠同時處理多個電子郵件請求而不影響性能,這使得 Node.js 成為將事務(wù)性電子郵件傳送集成到 Web 應(yīng)用程序中的理想選擇。此解決方案易于擴展,即使面對大量電子郵件流量也能應(yīng)對自如。
在本文中,您將學(xué)習(xí)如何在 Node.js 后端使用電子郵件 API 和 SMTP(簡單郵件傳輸協(xié)議)來發(fā)送電子郵件。我們將提供代碼示例,并探討這兩種方法的優(yōu)缺點。此外,我們還將分享一些最佳實踐,以確保您的 Node.js 實施既可靠又安全。
選擇Email API還是將 Nodemailer 與 SMTP 服務(wù)器一起使用,很大程度上取決于您的設(shè)置所需的特性和功能,以及您的技術(shù)能力。
如果您希望利用電子郵件模板、分析功能、抑制管理、入站路由等高級特性,那么Email API 無疑是更好的選擇。而如果您更愿意自行配置和管理 SMTP 服務(wù)器(并且您有時間這樣做),或者您需要一個更簡潔的電子郵件發(fā)送解決方案,那么 Nodemailer 可能是您的最佳選擇。
以下是對兩者進行比較的快速概述。
特征 | Email API | Nodemailer |
易用性 | 易于實施,但需要技術(shù)知識 | 易于實施,但需要一些技術(shù)知識。如果使用自己的 SMTP 服務(wù)器,則需要相當(dāng)多的配置。 |
可靠性 | 非常好的第三方服務(wù)可確保高送達率并處理重試 | 如果使用第三方服務(wù),則非常好,如果使用自己的 SMTP 服務(wù)器設(shè)置,則可能難以管理 |
可擴展性 | 旨在無縫處理大量電子郵件 | 各不相同,如果使用第三方服務(wù),通常非常好,否則,它取決于 SMTP 服務(wù)器的能力 |
成本 | 變量和基于使用情況 | 如果管理自己的 SMTP 服務(wù)器,則為低到中,如果使用第三方服務(wù),則為可變和基于使用情況 |
特征 | 分析、模板和列表管理等高級功能 | 專注于發(fā)送沒有高級功能的電子郵件 |
安全 | 內(nèi)置對 DKIM、SPF 和 DMARC 等安全協(xié)議的支持 | 安全性取決于 SMTP 服務(wù)器配置,如果使用第三方服務(wù),則通常很好 |
屬地 | 依賴第三方服務(wù)的正常運行時間和性能 | 依賴第三方服務(wù)的正常運行時間和性能,如果管理自己的服務(wù)器,則依賴更多控制 |
定制 | 取決于 API 提供商的功能和限制 | 取決于 SMTP 服務(wù)提供商的功能和限制。如果管理自己的服務(wù)器,可以提供完全控制 |
設(shè)置復(fù)雜性 | 與提供的 SDK 和 API 輕松集成 | 與 SMTP 提供商的憑據(jù)簡單集成,自我管理的 SMTP 服務(wù)器需要對 SMTP 設(shè)置進行更多設(shè)置和配置 |
社區(qū)支持 | 來自 API 提供商的大型社區(qū)和廣泛的文檔 | 廣泛使用,提供廣泛的文檔和社區(qū)支持 |
無論您選擇使用 Email API 還是 Nodemailer,都需要先熟悉 Node.js 以及一些基礎(chǔ)編碼。本教程將介紹如何使用 MailerSend email API 和 SMTP 服務(wù)來發(fā)送電子郵件,因此您需要先注冊一個 MailerSend 帳戶。
以下是快速執(zhí)行此操作的方法:
1. 注冊一個 MailerSend 帳戶。該服務(wù)是免費加入的,您將獲得 100 封免費電子郵件以及一個試用域,讓您能夠迅速開始設(shè)置。如果您對服務(wù)滿意,還可以訂閱 Free 計劃,每月最多可發(fā)送 3,000 封電子郵件,且無需支付任何費用。
2.注冊并驗證您的電子郵件地址后,接下來需要創(chuàng)建一個 API 令牌(如果您計劃使用電子郵件 API)或 SMTP 用戶和憑證(如果您計劃使用 Nodemailer 和 SMTP)。
要創(chuàng)建 API 令牌:
在控制面板中,單擊左側(cè)菜單中的 Integrations,然后單擊 API 令牌旁邊的 Manage。
在 API 令牌頁面上,單擊 Generate new token(生成新令牌),將出現(xiàn)一個用于創(chuàng)建令牌的彈出窗口。輸入可識別的名稱,選擇要為其創(chuàng)建令牌的域,并允許適當(dāng)?shù)脑L問權(quán)限。然后單擊 Create token(創(chuàng)建令牌)。
將生成您的 API 令牌。復(fù)制并保存或下載令牌。關(guān)閉此彈出窗口后,出于安全原因,您將無法再次查看此令牌。
要創(chuàng)建新的 SMTP 用戶和憑證:
在控制面板中,單擊 Domains (域) 中的左側(cè)菜單。如果您想使用自己的域,可以通過單擊 Add domain (添加域) 來添加一個域,也可以使用試用域。
在要使用的域旁邊,單擊 Manage(管理)。向下滾動到 SMTP 部分,然后單擊 Generate new user(生成新用戶)。將出現(xiàn)一個彈出窗口,為您的新 SMTP 用戶輸入一個可識別的名稱,然后單擊 Save user(保存用戶)。
然后,您將獲得 SMTP 憑據(jù),其中包括用戶名、密碼、服務(wù)器地址和端口。單擊 Save user(保存用戶)。然后,您可以將憑證保存在某個位置,或稍后通過單擊 Manage (管理) 來訪問它們。
現(xiàn)在,讓我們轉(zhuǎn)向在 Node.js 中使用電子郵件 API 發(fā)送電子郵件。使用 Email API 是發(fā)送電子郵件的強大且功能豐富的方式。盡管與 SMTP 一起使用某個軟件包仍需要一些技術(shù)知識,但使用 Email API 可以獲得更高級的功能和特性,這是值得的。
使用 MailerSend 的 API,您將獲得個性化、動態(tài)電子郵件模板、黑名單管理、分析、使用 SPF、DKIM 和 DMARC 安全協(xié)議的發(fā)件人身份驗證等功能。
如何開始使用:
1. 通過在系統(tǒng)上安裝 Node.js,確保您已準(zhǔn)備好 Node.js 環(huán)境。
然后,在項目目錄中運行“npm init”命令,并按照提示設(shè)置 package.json 文件,以創(chuàng)建一個新的 Node.js 項目。
2. 接下來,使用以下命令安裝 MailerSend 包:
npm install mailersend
要在代碼中使用 env 變量,請安裝 Dotenv 模塊:
npm install dotenv --save
在以下代碼示例中,我們將對 API 令牌使用此方法。要為您的 API 令牌定義變量,請在 Node.js 項目的根目錄中創(chuàng)建一個名為 .env 的 .env 文件,并將 MAILERSEND_API_TOKEN 變量添加到該文件中。該文件應(yīng)如下所示:
API_KEY=Your_API_Key_Here
讓我們看一下使用 MailerSend API 發(fā)送帶有 Node.js 的簡單 HTML 電子郵件所需的代碼。在此示例中,我們將發(fā)送一封試用注冊確認電子郵件,以確認用戶的試用訂閱,并向他們提供任何相關(guān)信息。
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的一個主要優(yōu)勢在于能夠輕松發(fā)送專業(yè)設(shè)計的電子郵件模板。在MailerSend平臺上,通過模板構(gòu)建器,您可以非常便捷地創(chuàng)建模板——無論是使用拖放編輯器、富文本編輯器,還是直接從HTML編輯器開始構(gòu)建。之后,您只需獲取模板的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);
})
個性化變量能夠幫助您根據(jù)導(dǎo)入的數(shù)據(jù)(例如收件人的姓名)為不同的收件人定制電子郵件內(nèi)容。在使用 MailerSend 時,您可以通過 {{var}} 的格式來定義變量,并將它們嵌入到電子郵件內(nèi)容中。
以下是一個示例代碼,展示了如何發(fā)送一封包含個性化內(nèi)容的電子郵件,通知用戶他們的試用期即將結(jié)束。
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);
})
當(dāng)Pam決定購買訂閱時,就到了發(fā)送她第一張發(fā)票的時候。為了發(fā)送帶有附件的電子郵件,我們將使用attachment類,并通過設(shè)置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調(diào)用,方便地實現(xiàn)個性化電子郵件的批量發(fā)送。這一功能幫助您規(guī)避了速率限制,并顯著提升了發(fā)送效率。
在此示例中,我們計劃向Pam和Dwight發(fā)送反饋請求。此類交易性電子郵件非常適合進行批量發(fā)送,因為其對時間的要求并不嚴(yán)格,可以隨時進行。
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);
})
如果您需要在特定時間或日期發(fā)送電子郵件,則可以使用 .setSendAt 參數(shù)和 Unix 時間戳來安排它。以下是我們發(fā)送給 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()
方法用于獲取當(dāng)前時間(以毫秒為單位)。接著,通過向當(dāng)前時間添加 30 * 60 * 1000
毫秒,計算出從當(dāng)前時刻起30分鐘后的時間點。
Date
對象的 getTime()
方法返回自 Unix 紀(jì)元以來的毫秒數(shù)。為了將其轉(zhuǎn)換為以秒為單位的 Unix 時間戳,我們將毫秒數(shù)除以 1000
。
Math.floor()
?函數(shù)用于將得到的時間戳向下舍入到最接近的整數(shù),因為 Unix 時間戳必須是整數(shù)。最后,使用?EmailParams
?的?setSendAt
?方法來設(shè)置計劃發(fā)送時間,而該時間是通過前面計算出的 Unix 時間戳來確定的。
如果您想使用 SMTP,Nodemailer 無疑是一個很好的解決方案。Node.js 模塊允許您以簡單有效的方式將電子郵件發(fā)送集成到 Node.js 應(yīng)用程序中,同時支持身份驗證機制以確保與 SMTP 服務(wù)器的連接安全。
簡而言之:
注意:
雖然您可以直接使用 SMTP 服務(wù)器在 Node.js 中發(fā)送電子郵件,但這種方法缺少了像 Nodemailer 這樣的庫所能提供的豐富安全功能,可能會使您的應(yīng)用程序面臨網(wǎng)絡(luò)攻擊和數(shù)據(jù)泄露的風(fēng)險。
所以讓我們開始吧。
1. 首先,請確保您的系統(tǒng)上已經(jīng)安裝了 Node.js,這是進行后續(xù)操作的基礎(chǔ)。
然后,在您的項目目錄中運行 npm init 命令,并根據(jù)提示完成 package.json 文件的設(shè)置,從而創(chuàng)建一個新的 Node.js 項目。
2. 安裝 Nodemailer 模塊:
npm install nodemailer
3. 在項目根目錄中為您的 MailerSend SMTP 憑證創(chuàng)建一個 .env 文件 — 如果您需要復(fù)習(xí)如何創(chuàng)建 SMTP 用戶和檢索憑證,請?zhí)乇竟?jié)的開頭或閱讀我們的指南如何使用 SMTP 發(fā)送電子郵件。
您需要添加 SMTP 服務(wù)器地址、端口、用戶名和密碼:
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. 發(fā)送電子郵件!以下是使用我們的試用確認電子郵件的代碼示例:
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 數(shù)組:
attachments: [
{
filename: 'invoice.pdf',
path: '/path/to/invoice.pdf',
},
]
還可以通過修改電子郵件內(nèi)容并定義收件人的個性化數(shù)據(jù),在電子郵件中包含個性化。這是該反饋請求,其中為收件人的姓名設(shè)置了個性化變量:
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);
若操作得當(dāng)并遵循最佳實踐,Node.js 將成為一種高效、可靠且安全的電子郵件發(fā)送方式。如果您已準(zhǔn)備好開始使用,請牢記以下最佳實踐,以確保順利實施并提升電子郵件發(fā)送體驗。
盡管我們因Email API的靈活性和高級功能而對其青睞有加,但我們深知它并非適用于所有人。SMTP和電子郵件API在易用性、功能性、可靠性和安全性方面各有千秋。若您尋求一種簡潔且經(jīng)濟高效的解決方案,SMTP可能是您的理想之選。然而,若您期望獲得更多功能、高級工作流程及跟蹤能力,那么API將是您的最佳選擇。
此外,管理自己的SMTP服務(wù)器要復(fù)雜得多,需要您自行實施安全措施以確保發(fā)送安全。與諸如MailerSend這樣的第三方提供商合作,則意味著送達率、安全性及其他所有問題都將得到妥善處理。
MailerSend的Email API和SMTP均構(gòu)建于同一強大、安全且可靠的發(fā)送基礎(chǔ)設(shè)施之上,并提供對活動和分析的訪問權(quán)限。因此,無論您選擇使用我們的API還是保持簡單的SMTP方式,都可以放心,您的電子郵件將得到妥善處理。
為了集成電子郵件發(fā)送功能,您需要使用一些敏感數(shù)據(jù),比如 API 密鑰和 SMTP 憑據(jù)。這些數(shù)據(jù)若直接暴露在代碼中,會帶來安全風(fēng)險!通過將它們保存在?.env
?文件中,您可以在代碼中隱藏這些數(shù)據(jù),從而避免泄露。此外,這也使得管理電子郵件發(fā)送變得更加便捷,因為您無需在每個電子郵件發(fā)送的腳本中硬編碼 API 密鑰或 SMTP 憑據(jù),只需在?.env
?文件中更新相關(guān)數(shù)據(jù)即可。
為可能出現(xiàn)的故障做好準(zhǔn)備是構(gòu)建任何優(yōu)秀系統(tǒng)的關(guān)鍵一環(huán)。在電子郵件發(fā)送的場景中,您需要確保應(yīng)用程序能夠妥善處理任何錯誤,避免崩潰或出現(xiàn)意外的響應(yīng)。為此,您可以使用 try-catch 塊或 promise 錯誤處理機制來捕獲并記錄任何錯誤。這樣做不僅能提升應(yīng)用程序的可靠性,還能讓故障排除工作變得更加輕松。
速率限制涉及使用 Bottleneck 等軟件包來限制電子郵件發(fā)送。下面是一個示例:
import Bottleneck from 'bottleneck';
const limiter = new Bottleneck({
minTime: 100 / maxEmailsPerSecond,
});
limiter.schedule(() => transporter.sendMail(mailOptions));
這樣做可以防止你的應(yīng)用壓垮你的電子郵件服務(wù)器,并避免你的電子郵件服務(wù)提供商設(shè)置的任何速率限制。
對電子郵件地址進行實時驗證,能夠優(yōu)化您的收件人列表,使其保持高效且持久,進而幫助您維持較高的電子郵件送達率。盡管您可以通過 JavaScript 中的正則表達式來檢查電子郵件地址的格式是否正確,但這僅僅停留在表面層面。為了更深入地檢查不存在的郵箱、拼寫錯誤以及一次性電子郵件等問題,推薦使用電子郵件驗證服務(wù)。
您可以查閱相關(guān)文章,了解如何借助 MailerSend 開始進行實時電子郵件驗證。
電子郵件模板能夠助您發(fā)送符合品牌調(diào)性的專業(yè)設(shè)計郵件。同時,它們還簡化了電子郵件內(nèi)容的管理流程,并有助于保持代碼的清晰與簡潔。您只需構(gòu)建模板,并將其單獨存儲,隨后在發(fā)送電子郵件時將其加載即可。
在使用 MailerSend 時,這一過程尤為簡便。MailerSend 提供了三個電子郵件構(gòu)建器選項,包括拖放、豐富文本以及 HTML。構(gòu)建模板后,您只需檢索模板 ID,并將其添加到您的代碼中即可。
或許您會認為電子郵件分析僅僅是業(yè)務(wù)負責(zé)人關(guān)注的事項,用以查看電子郵件的轉(zhuǎn)化次數(shù)。但實際上,分析能夠為您提供關(guān)鍵的性能洞察,幫助您識別送達率方面存在的問題。
更重要的是,借助MailerSend,您可以輕松利用webhook設(shè)置通知,這樣一旦有任何異常情況發(fā)生,您就能實時了解,而無需親自查看分析儀表板。
利用 Email API 或 Nodemailer 是通過 Node.js 發(fā)送電子郵件的常用且明智之選,這背后有著充分的理由。當(dāng)您選擇與可靠的電子郵件服務(wù)提供商合作時,幾乎可以確保不會出錯。而且,作為 JavaScript 運行時的一部分,這種方式是將電子郵件發(fā)送功能集成到 JavaScript 應(yīng)用程序中的最為簡便的方法。
若您正在尋找一個既能保證卓越送達率又強大且安全的 Email API,那么 MailerSend 無疑是一個值得嘗試的選擇。
原文鏈接:https://www.mailersend.com/blog/send-email-nodejs