Node.js 是一個(gè)功能強(qiáng)大的 JavaScript 運(yùn)行環(huán)境,以其無(wú)阻塞、事件驅(qū)動(dòng)的架構(gòu)和出色的異步操作能力(包括電子郵件處理)而著稱(chēng)。

它能夠同時(shí)處理多個(gè)電子郵件請(qǐng)求而不影響性能,這使得 Node.js 成為將事務(wù)性電子郵件傳送集成到 Web 應(yīng)用程序中的理想選擇。此解決方案易于擴(kuò)展,即使面對(duì)大量電子郵件流量也能應(yīng)對(duì)自如。

在本文中,您將學(xué)習(xí)如何在 Node.js 后端使用電子郵件 API 和 SMTP(簡(jiǎn)單郵件傳輸協(xié)議)來(lái)發(fā)送電子郵件。我們將提供代碼示例,并探討這兩種方法的優(yōu)缺點(diǎn)。此外,我們還將分享一些最佳實(shí)踐,以確保您的 Node.js 實(shí)施既可靠又安全。

您應(yīng)該使用哪個(gè):API 還是 Nodemailer (SMTP)?

選擇Email API還是將 Nodemailer 與 SMTP 服務(wù)器一起使用,很大程度上取決于您的設(shè)置所需的特性和功能,以及您的技術(shù)能力。

如果您希望利用電子郵件模板、分析功能、抑制管理、入站路由等高級(jí)特性,那么Email API 無(wú)疑是更好的選擇。而如果您更愿意自行配置和管理 SMTP 服務(wù)器(并且您有時(shí)間這樣做),或者您需要一個(gè)更簡(jiǎn)潔的電子郵件發(fā)送解決方案,那么 Nodemailer 可能是您的最佳選擇。

以下是對(duì)兩者進(jìn)行比較的快速概述。

特征Email APINodemailer
易用性易于實(shí)施,但需要技術(shù)知識(shí)易于實(shí)施,但需要一些技術(shù)知識(shí)。如果使用自己的 SMTP 服務(wù)器,則需要相當(dāng)多的配置。
可靠性非常好的第三方服務(wù)可確保高送達(dá)率并處理重試如果使用第三方服務(wù),則非常好,如果使用自己的 SMTP 服務(wù)器設(shè)置,則可能難以管理
可擴(kuò)展性旨在無(wú)縫處理大量電子郵件各不相同,如果使用第三方服務(wù),通常非常好,否則,它取決于 SMTP 服務(wù)器的能力
成本變量和基于使用情況如果管理自己的 SMTP 服務(wù)器,則為低到中,如果使用第三方服務(wù),則為可變和基于使用情況
特征分析、模板和列表管理等高級(jí)功能專(zhuān)注于發(fā)送沒(méi)有高級(jí)功能的電子郵件
安全內(nèi)置對(duì) DKIM、SPF 和 DMARC 等安全協(xié)議的支持安全性取決于 SMTP 服務(wù)器配置,如果使用第三方服務(wù),則通常很好
屬地依賴(lài)第三方服務(wù)的正常運(yùn)行時(shí)間和性能依賴(lài)第三方服務(wù)的正常運(yùn)行時(shí)間和性能,如果管理自己的服務(wù)器,則依賴(lài)更多控制
定制取決于 API 提供商的功能和限制取決于 SMTP 服務(wù)提供商的功能和限制。如果管理自己的服務(wù)器,可以提供完全控制
設(shè)置復(fù)雜性與提供的 SDK 和 API 輕松集成與 SMTP 提供商的憑據(jù)簡(jiǎn)單集成,自我管理的 SMTP 服務(wù)器需要對(duì) SMTP 設(shè)置進(jìn)行更多設(shè)置和配置
社區(qū)支持來(lái)自 API 提供商的大型社區(qū)和廣泛的文檔廣泛使用,提供廣泛的文檔和社區(qū)支持

如何使用 Node.js 發(fā)送電子郵件

無(wú)論您選擇使用 Email API 還是 Nodemailer,都需要先熟悉 Node.js 以及一些基礎(chǔ)編碼。本教程將介紹如何使用 MailerSend email API 和 SMTP 服務(wù)來(lái)發(fā)送電子郵件,因此您需要先注冊(cè)一個(gè) MailerSend 帳戶(hù)。

以下是快速執(zhí)行此操作的方法:

1. 注冊(cè)一個(gè) MailerSend 帳戶(hù)。該服務(wù)是免費(fèi)加入的,您將獲得 100 封免費(fèi)電子郵件以及一個(gè)試用域,讓您能夠迅速開(kāi)始設(shè)置。如果您對(duì)服務(wù)滿(mǎn)意,還可以訂閱 Free 計(jì)劃,每月最多可發(fā)送 3,000 封電子郵件,且無(wú)需支付任何費(fèi)用。

2.注冊(cè)并驗(yàn)證您的電子郵件地址后,接下來(lái)需要?jiǎng)?chuàng)建一個(gè) API 令牌(如果您計(jì)劃使用電子郵件 API)或 SMTP 用戶(hù)和憑證(如果您計(jì)劃使用 Nodemailer 和 SMTP)。

要?jiǎng)?chuàng)建 API 令牌:

在控制面板中,單擊左側(cè)菜單中的 Integrations,然后單擊 API 令牌旁邊的 Manage

在 API 令牌頁(yè)面上,單擊 Generate new token(生成新令牌),將出現(xiàn)一個(gè)用于創(chuàng)建令牌的彈出窗口。輸入可識(shí)別的名稱(chēng),選擇要為其創(chuàng)建令牌的域,并允許適當(dāng)?shù)脑L(fǎng)問(wèn)權(quán)限。然后單擊 Create token(創(chuàng)建令牌)。

將生成您的 API 令牌。復(fù)制并保存或下載令牌。關(guān)閉此彈出窗口后,出于安全原因,您將無(wú)法再次查看此令牌。

要?jiǎng)?chuàng)建新的 SMTP 用戶(hù)和憑證:

在控制面板中,單擊 Domains (域) 中的左側(cè)菜單。如果您想使用自己的域,可以通過(guò)單擊 Add domain (添加域) 來(lái)添加一個(gè)域,也可以使用試用域。

在要使用的域旁邊,單擊 Manage(管理)。向下滾動(dòng)到 SMTP 部分,然后單擊 Generate new user(生成新用戶(hù))。將出現(xiàn)一個(gè)彈出窗口,為您的新 SMTP 用戶(hù)輸入一個(gè)可識(shí)別的名稱(chēng),然后單擊 Save user(保存用戶(hù))。

然后,您將獲得 SMTP 憑據(jù),其中包括用戶(hù)名、密碼、服務(wù)器地址和端口。單擊 Save user(保存用戶(hù))。然后,您可以將憑證保存在某個(gè)位置,或稍后通過(guò)單擊 Manage (管理) 來(lái)訪(fǎng)問(wèn)它們。

使用電子郵件 API 在 Node.js 中發(fā)送電子郵件

現(xiàn)在,讓我們轉(zhuǎn)向在 Node.js 中使用電子郵件 API 發(fā)送電子郵件。使用 Email API 是發(fā)送電子郵件的強(qiáng)大且功能豐富的方式。盡管與 SMTP 一起使用某個(gè)軟件包仍需要一些技術(shù)知識(shí),但使用 Email API 可以獲得更高級(jí)的功能和特性,這是值得的。

使用 MailerSend 的 API,您將獲得個(gè)性化、動(dòng)態(tài)電子郵件模板、黑名單管理、分析、使用 SPF、DKIM 和 DMARC 安全協(xié)議的發(fā)件人身份驗(yàn)證等功能。

如何開(kāi)始使用:

1. 通過(guò)在系統(tǒng)上安裝 Node.js,確保您已準(zhǔn)備好 Node.js 環(huán)境。

然后,在項(xiàng)目目錄中運(yùn)行“npm init”命令,并按照提示設(shè)置 package.json 文件,以創(chuàng)建一個(gè)新的 Node.js 項(xiàng)目。

2. 接下來(lái),使用以下命令安裝 MailerSend 包:

npm install mailersend

要在代碼中使用 env 變量,請(qǐng)安裝 Dotenv 模塊:

npm install dotenv --save

在以下代碼示例中,我們將對(duì) API 令牌使用此方法。要為您的 API 令牌定義變量,請(qǐng)?jiān)?Node.js 項(xiàng)目的根目錄中創(chuàng)建一個(gè)名為 .env 的 .env 文件,并將 MAILERSEND_API_TOKEN 變量添加到該文件中。該文件應(yīng)如下所示:

API_KEY=Your_API_Key_Here

如何發(fā)送 HTML 電子郵件

讓我們看一下使用 MailerSend API 發(fā)送帶有 Node.js 的簡(jiǎn)單 HTML 電子郵件所需的代碼。在此示例中,我們將發(fā)送一封試用注冊(cè)確認(rèn)電子郵件,以確認(rèn)用戶(hù)的試用訂閱,并向他們提供任何相關(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 對(duì)象以包含這些收件人。以下是添加的 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);
})

如何發(fā)送基于模板的電子郵件

使用電子郵件API的一個(gè)主要優(yōu)勢(shì)在于能夠輕松發(fā)送專(zhuān)業(yè)設(shè)計(jì)的電子郵件模板。在MailerSend平臺(tái)上,通過(guò)模板構(gòu)建器,您可以非常便捷地創(chuàng)建模板——無(wú)論是使用拖放編輯器、富文本編輯器,還是直接從HTML編輯器開(kāi)始構(gòu)建。之后,您只需獲取模板的ID,并將其整合到您的代碼中即可。

以下是我們使用模板時(shí)免費(fèi)試用電子郵件的代碼:

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);
})

如何發(fā)送個(gè)性化電子郵件

個(gè)性化變量能夠幫助您根據(jù)導(dǎo)入的數(shù)據(jù)(例如收件人的姓名)為不同的收件人定制電子郵件內(nèi)容。在使用 MailerSend 時(shí),您可以通過(guò) {{var}} 的格式來(lái)定義變量,并將它們嵌入到電子郵件內(nèi)容中。

以下是一個(gè)示例代碼,展示了如何發(fā)送一封包含個(gè)性化內(nèi)容的電子郵件,通知用戶(hù)他們的試用期即將結(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);
})

如何發(fā)送帶有附件的電子郵件

當(dāng)Pam決定購(gòu)買(mǎi)訂閱時(shí),就到了發(fā)送她第一張發(fā)票的時(shí)候。為了發(fā)送帶有附件的電子郵件,我們將使用attachment類(lèi),并通過(guò)設(shè)置content、filename和type屬性來(lái)定義該附件。

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);
})

如何批量發(fā)送電子郵件

MailerSend提供的批量電子郵件功能,能夠通過(guò)一個(gè)單一的API調(diào)用,方便地實(shí)現(xiàn)個(gè)性化電子郵件的批量發(fā)送。這一功能幫助您規(guī)避了速率限制,并顯著提升了發(fā)送效率。

在此示例中,我們計(jì)劃向Pam和Dwight發(fā)送反饋請(qǐng)求。此類(lèi)交易性電子郵件非常適合進(jìn)行批量發(fā)送,因?yàn)槠鋵?duì)時(shí)間的要求并不嚴(yán)格,可以隨時(shí)進(jì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ā)送

如果您需要在特定時(shí)間或日期發(fā)送電子郵件,則可以使用 .setSendAt 參數(shù)和 Unix 時(shí)間戳來(lái)安排它。以下是我們發(fā)送給 Pam 和 Dwight 的維護(hù)通知電子郵件的代碼示例。

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)前時(shí)間(以毫秒為單位)。接著,通過(guò)向當(dāng)前時(shí)間添加 30 * 60 * 1000 毫秒,計(jì)算出從當(dāng)前時(shí)刻起30分鐘后的時(shí)間點(diǎn)。

Date 對(duì)象的 getTime() 方法返回自 Unix 紀(jì)元以來(lái)的毫秒數(shù)。為了將其轉(zhuǎn)換為以秒為單位的 Unix 時(shí)間戳,我們將毫秒數(shù)除以 1000

Math.floor()?函數(shù)用于將得到的時(shí)間戳向下舍入到最接近的整數(shù),因?yàn)?Unix 時(shí)間戳必須是整數(shù)。最后,使用?EmailParams?的?setSendAt?方法來(lái)設(shè)置計(jì)劃發(fā)送時(shí)間,而該時(shí)間是通過(guò)前面計(jì)算出的 Unix 時(shí)間戳來(lái)確定的。

使用 SMTP 和 Nodemailer 以 Node.js 發(fā)送電子郵件

如果您想使用 SMTP,Nodemailer 無(wú)疑是一個(gè)很好的解決方案。Node.js 模塊允許您以簡(jiǎn)單有效的方式將電子郵件發(fā)送集成到 Node.js 應(yīng)用程序中,同時(shí)支持身份驗(yàn)證機(jī)制以確保與 SMTP 服務(wù)器的連接安全。

簡(jiǎn)而言之:

注意:

雖然您可以直接使用 SMTP 服務(wù)器在 Node.js 中發(fā)送電子郵件,但這種方法缺少了像 Nodemailer 這樣的庫(kù)所能提供的豐富安全功能,可能會(huì)使您的應(yīng)用程序面臨網(wǎng)絡(luò)攻擊和數(shù)據(jù)泄露的風(fēng)險(xiǎn)。

所以讓我們開(kāi)始吧。

1. 首先,請(qǐng)確保您的系統(tǒng)上已經(jīng)安裝了 Node.js,這是進(jìn)行后續(xù)操作的基礎(chǔ)。

然后,在您的項(xiàng)目目錄中運(yùn)行 npm init 命令,并根據(jù)提示完成 package.json 文件的設(shè)置,從而創(chuàng)建一個(gè)新的 Node.js 項(xiàng)目。

2. 安裝 Nodemailer 模塊:

npm install nodemailer

3. 在項(xiàng)目根目錄中為您的 MailerSend SMTP 憑證創(chuàng)建一個(gè) .env 文件 — 如果您需要復(fù)習(xí)如何創(chuàng)建 SMTP 用戶(hù)和檢索憑證,請(qǐng)?zhí)乇竟?jié)的開(kāi)頭或閱讀我們的指南如何使用 SMTP 發(fā)送電子郵件。

您需要添加 SMTP 服務(wù)器地址、端口、用戶(hù)名和密碼:

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ā)送電子郵件!以下是使用我們的試用確認(rèn)電子郵件的代碼示例:

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 中包含一個(gè) attachments 數(shù)組:

attachments: [
{
filename: 'invoice.pdf',
path: '/path/to/invoice.pdf',
},
]

還可以通過(guò)修改電子郵件內(nèi)容并定義收件人的個(gè)性化數(shù)據(jù),在電子郵件中包含個(gè)性化。這是該反饋請(qǐng)求,其中為收件人的姓名設(shè)置了個(gè)性化變量:

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 中發(fā)送電子郵件的最佳實(shí)踐

若操作得當(dāng)并遵循最佳實(shí)踐,Node.js 將成為一種高效、可靠且安全的電子郵件發(fā)送方式。如果您已準(zhǔn)備好開(kāi)始使用,請(qǐng)牢記以下最佳實(shí)踐,以確保順利實(shí)施并提升電子郵件發(fā)送體驗(yàn)。

1. 選擇正確的發(fā)送方式

盡管我們因Email API的靈活性和高級(jí)功能而對(duì)其青睞有加,但我們深知它并非適用于所有人。SMTP和電子郵件API在易用性、功能性、可靠性和安全性方面各有千秋。若您尋求一種簡(jiǎn)潔且經(jīng)濟(jì)高效的解決方案,SMTP可能是您的理想之選。然而,若您期望獲得更多功能、高級(jí)工作流程及跟蹤能力,那么API將是您的最佳選擇。

此外,管理自己的SMTP服務(wù)器要復(fù)雜得多,需要您自行實(shí)施安全措施以確保發(fā)送安全。與諸如MailerSend這樣的第三方提供商合作,則意味著送達(dá)率、安全性及其他所有問(wèn)題都將得到妥善處理。

MailerSend的Email API和SMTP均構(gòu)建于同一強(qiáng)大、安全且可靠的發(fā)送基礎(chǔ)設(shè)施之上,并提供對(duì)活動(dòng)和分析的訪(fǎng)問(wèn)權(quán)限。因此,無(wú)論您選擇使用我們的API還是保持簡(jiǎn)單的SMTP方式,都可以放心,您的電子郵件將得到妥善處理。

2. 使用環(huán)境變量

為了集成電子郵件發(fā)送功能,您需要使用一些敏感數(shù)據(jù),比如 API 密鑰和 SMTP 憑據(jù)。這些數(shù)據(jù)若直接暴露在代碼中,會(huì)帶來(lái)安全風(fēng)險(xiǎn)!通過(guò)將它們保存在?.env?文件中,您可以在代碼中隱藏這些數(shù)據(jù),從而避免泄露。此外,這也使得管理電子郵件發(fā)送變得更加便捷,因?yàn)槟鸁o(wú)需在每個(gè)電子郵件發(fā)送的腳本中硬編碼 API 密鑰或 SMTP 憑據(jù),只需在?.env?文件中更新相關(guān)數(shù)據(jù)即可。

3. 實(shí)施充分的錯(cuò)誤處理

為可能出現(xiàn)的故障做好準(zhǔn)備是構(gòu)建任何優(yōu)秀系統(tǒng)的關(guān)鍵一環(huán)。在電子郵件發(fā)送的場(chǎng)景中,您需要確保應(yīng)用程序能夠妥善處理任何錯(cuò)誤,避免崩潰或出現(xiàn)意外的響應(yīng)。為此,您可以使用 try-catch 塊或 promise 錯(cuò)誤處理機(jī)制來(lái)捕獲并記錄任何錯(cuò)誤。這樣做不僅能提升應(yīng)用程序的可靠性,還能讓故障排除工作變得更加輕松。

4. 使用速率限制

速率限制涉及使用 Bottleneck 等軟件包來(lái)限制電子郵件發(fā)送。下面是一個(gè)示例:

import Bottleneck from 'bottleneck';

const limiter = new Bottleneck({
minTime: 100 / maxEmailsPerSecond,
});

limiter.schedule(() => transporter.sendMail(mailOptions));

這樣做可以防止你的應(yīng)用壓垮你的電子郵件服務(wù)器,并避免你的電子郵件服務(wù)提供商設(shè)置的任何速率限制。

5. 驗(yàn)證電子郵件地址

對(duì)電子郵件地址進(jìn)行實(shí)時(shí)驗(yàn)證,能夠優(yōu)化您的收件人列表,使其保持高效且持久,進(jìn)而幫助您維持較高的電子郵件送達(dá)率。盡管您可以通過(guò) JavaScript 中的正則表達(dá)式來(lái)檢查電子郵件地址的格式是否正確,但這僅僅停留在表面層面。為了更深入地檢查不存在的郵箱、拼寫(xiě)錯(cuò)誤以及一次性電子郵件等問(wèn)題,推薦使用電子郵件驗(yàn)證服務(wù)。

您可以查閱相關(guān)文章,了解如何借助 MailerSend 開(kāi)始進(jìn)行實(shí)時(shí)電子郵件驗(yàn)證。

6. 使用模板

電子郵件模板能夠助您發(fā)送符合品牌調(diào)性的專(zhuān)業(yè)設(shè)計(jì)郵件。同時(shí),它們還簡(jiǎn)化了電子郵件內(nèi)容的管理流程,并有助于保持代碼的清晰與簡(jiǎn)潔。您只需構(gòu)建模板,并將其單獨(dú)存儲(chǔ),隨后在發(fā)送電子郵件時(shí)將其加載即可。

在使用 MailerSend 時(shí),這一過(guò)程尤為簡(jiǎn)便。MailerSend 提供了三個(gè)電子郵件構(gòu)建器選項(xiàng),包括拖放、豐富文本以及 HTML。構(gòu)建模板后,您只需檢索模板 ID,并將其添加到您的代碼中即可。

突出顯示模板 ID 的 MailerSend 模板。

7. 監(jiān)控電子郵件的送達(dá)率和性能

或許您會(huì)認(rèn)為電子郵件分析僅僅是業(yè)務(wù)負(fù)責(zé)人關(guān)注的事項(xiàng),用以查看電子郵件的轉(zhuǎn)化次數(shù)。但實(shí)際上,分析能夠?yàn)槟峁╆P(guān)鍵的性能洞察,幫助您識(shí)別送達(dá)率方面存在的問(wèn)題。

更重要的是,借助MailerSend,您可以輕松利用webhook設(shè)置通知,這樣一旦有任何異常情況發(fā)生,您就能實(shí)時(shí)了解,而無(wú)需親自查看分析儀表板。

MailerSend 分析。

簡(jiǎn)單、高效且可靠的電子郵件發(fā)送方案

利用 Email API 或 Nodemailer 是通過(guò) Node.js 發(fā)送電子郵件的常用且明智之選,這背后有著充分的理由。當(dāng)您選擇與可靠的電子郵件服務(wù)提供商合作時(shí),幾乎可以確保不會(huì)出錯(cuò)。而且,作為 JavaScript 運(yùn)行時(shí)的一部分,這種方式是將電子郵件發(fā)送功能集成到 JavaScript 應(yīng)用程序中的最為簡(jiǎn)便的方法。

若您正在尋找一個(gè)既能保證卓越送達(dá)率又強(qiáng)大且安全的 Email API,那么 MailerSend 無(wú)疑是一個(gè)值得嘗試的選擇。

原文鏈接:https://www.mailersend.com/blog/send-email-nodejs

熱門(mén)推薦
一個(gè)賬號(hào)試用1000+ API
助力AI無(wú)縫鏈接物理世界 · 無(wú)需多次注冊(cè)
3000+提示詞助力AI大模型
和專(zhuān)業(yè)工程師共享工作效率翻倍的秘密
返回頂部
上一篇
如何使用FMP API在Telegram上即時(shí)獲取加密貨幣更新
下一篇
監(jiān)控使用 Apollo 和 Express 構(gòu)建的 GraphQL API
国内精品久久久久影院日本,日本中文字幕视频,99久久精品99999久久,又粗又大又黄又硬又爽毛片
thepron国产精品| 中文字幕在线观看一区二区| 99这里只有精品| 久久精品欧美日韩| 欧美tickling网站挠脚心| 亚洲综合视频网| 五月天久久比比资源色| 在线精品视频免费播放| 自拍偷拍欧美精品| 在线观看欧美日本| 亚洲国产视频a| 91麻豆精品国产综合久久久久久| 欧美成人精品福利| 国产原创一区二区| 中文字幕一区二区三区视频| 99久久伊人久久99| 欧美不卡123| 99国产精品久久久久| 一区二区三区不卡在线观看| 日韩精品一区二区三区在线播放 | 国产午夜亚洲精品不卡| 不卡一区二区在线| 有坂深雪av一区二区精品| 日本网站在线观看一区二区三区| 奇米四色…亚洲| 欧美日韩三级一区| 欧美一级xxx| 337p日本欧洲亚洲大胆精品| 在线观看av一区| 国产成人aaa| 欧美va亚洲va国产综合| 精品一区二区在线视频| 《视频一区视频二区| 欧美日韩美女一区二区| 亚洲视频一区二区免费在线观看| 欧美一二三区在线| 不卡视频在线看| 精品中文字幕一区二区小辣椒| 国产精品麻豆欧美日韩ww| 欧美色手机在线观看| 国产麻豆一精品一av一免费| 亚洲一区二三区| 国产精品三级在线观看| 9191成人精品久久| 99精品热视频| 黄色日韩三级电影| 美女www一区二区| 亚洲一区二区美女| 日本精品免费观看高清观看| 九九国产精品视频| 性感美女极品91精品| 亚洲一二三四区| 中文字幕免费不卡| 色婷婷久久久亚洲一区二区三区| 成人精品国产福利| 国产成人午夜电影网| 国产成人av电影在线播放| 毛片一区二区三区| 乱中年女人伦av一区二区| 久久精品99国产精品日本| 天天综合天天做天天综合| 亚洲国产日韩综合久久精品| 亚洲国产日韩a在线播放| 最新中文字幕一区二区三区| 亚洲免费成人av| 亚洲va欧美va国产va天堂影院| 亚洲激情中文1区| 亚洲日本va在线观看| 欧美羞羞免费网站| 久久99精品久久只有精品| 一区二区三区美女| 精品国产一区二区三区久久久蜜月| 九色综合国产一区二区三区| 日韩和欧美的一区| 国产精品麻豆欧美日韩ww| 国产精品视频你懂的| 国产成人aaa| 99天天综合性| 国产精品1区二区.| 色94色欧美sute亚洲线路二| 一区二区高清免费观看影视大全| 一区在线观看视频| 久久精品免费看| 国产在线精品一区二区不卡了 | 亚洲蜜臀av乱码久久精品| 国产·精品毛片| 久久久久国产精品麻豆ai换脸 | 不卡av在线网| 欧洲一区在线电影| 日韩精品一区二区三区在线| 国产精品免费人成网站| 麻豆成人91精品二区三区| 99久久久久久99| 久久先锋影音av| 亚洲成人免费视频| 在线视频中文字幕一区二区| 欧美精品一区二区三区很污很色的| 亚洲成a人片在线不卡一二三区| 国产毛片精品视频| 欧美精品一区二区精品网| 亚洲bdsm女犯bdsm网站| 在线日韩一区二区| 日韩一区欧美一区| 久久精品亚洲乱码伦伦中文| 午夜精品久久久久久不卡8050 | 久久久久99精品一区| 成人av电影免费在线播放| 日韩精品综合一本久道在线视频| 蜜桃在线一区二区三区| 精品久久久久久久久久久久包黑料 | av一二三不卡影片| 国产91精品一区二区麻豆网站 | 亚洲主播在线播放| 国产91精品精华液一区二区三区| 欧美视频精品在线| 亚洲美女免费视频| 成人高清视频免费观看| 久久久综合激的五月天| 久久精品免费看| 69久久夜色精品国产69蝌蚪网| 亚洲欧洲在线观看av| 成人一区二区视频| 欧美国产激情二区三区| 风流少妇一区二区| 亚洲欧洲国产专区| 图片区日韩欧美亚洲| 成人伦理片在线| 不卡在线观看av| 久久久91精品国产一区二区精品| 国产综合成人久久大片91| 亚洲精品在线观看视频| 国产精品一区三区| 最新国产成人在线观看| 色综合久久天天综合网| 一二三区精品福利视频| 欧美色综合网站| 日韩va欧美va亚洲va久久| 日韩午夜在线影院| 懂色av中文一区二区三区| 国产精品美女久久久久av爽李琼| 9i看片成人免费高清| 亚洲图片欧美色图| 日韩欧美国产一区二区三区| 国产乱码一区二区三区| 中文乱码免费一区二区| 欧美视频一区二| 久99久精品视频免费观看| 日韩欧美高清dvd碟片| 成人av在线播放网址| 午夜精品久久久久久不卡8050| 国产亚洲精品超碰| 在线不卡的av| 成人av免费在线播放| 肉色丝袜一区二区| 日韩欧美一级特黄在线播放| 国内外成人在线| 亚洲午夜电影在线观看| 亚洲午夜一区二区| 日韩欧美色综合网站| 欧美色网站导航| 日韩片之四级片| 日本一区二区三区国色天香 | 精品国产91乱码一区二区三区 | 久久福利资源站| 99久久婷婷国产综合精品电影 | 欧美日韩一区高清| 国产日韩欧美不卡在线| 亚洲二区在线视频| 国产成人小视频| 69堂精品视频| 亚洲精品高清视频在线观看| 欧美bbbbb| 51精品久久久久久久蜜臀| 欧美疯狂做受xxxx富婆| 日韩理论片中文av| 极品销魂美女一区二区三区| 欧美欧美欧美欧美| 日韩一区精品视频| 欧美午夜精品一区二区三区| 亚洲免费伊人电影| 在线观看av一区| 日本视频一区二区三区| 日韩一区二区三区电影| 亚洲国产精品久久久男人的天堂| 99久久亚洲一区二区三区青草| 中文字幕av资源一区| 成人黄页在线观看| 亚洲成av人在线观看| 在线观看免费成人| 日本va欧美va欧美va精品| 亚洲精品在线观| 大美女一区二区三区| 亚洲国产日韩精品| 欧美韩日一区二区三区| 欧美大度的电影原声| 蜜臀久久99精品久久久久久9 | 一本到不卡免费一区二区| 三级不卡在线观看| 天天色 色综合| 亚洲国产一区二区三区青草影视|