44
loading...
This website collects cookies to deliver better user experience
mkdir email-nodeapp && cd email-nodeapp
npm init -y
package.json
file using the npm init
command. The -y
flag is there to skip the interactive back-and-forth questions by npm.npm install nodemailer
createTransport
function specifies which method you want to use for sending email. It takes the connection data and credentials as an argument. In this case, since SMTP is the preferred transport, you will need to define an SMTP host, port, and credential password for accessing a host SMTP server.email.js
file and add the following:const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
host: 'smtp.mailtrap.io',
port: 2525,
auth: {
user: "<user>",
pass: "<pass>"
}
})
sendMail
method of Nodemailer’s createTransport
function.email.js
:message = {
from: "[email protected]",
to: "[email protected]",
subject: "Subject",
text: "Hello SMTP Email"
}
transporter.sendMail(message, **function**(err, info) {
if (err) {
console.log(err)
} else {
console.log(info);
}
html
attribute to your message object like so:message = {
from: "[email protected]",
to: "[email protected]",
subject: "Subject",
html: "<h1>Hello SMTP Email</h1>"
}
node email.js
npm install --save @sendgrid/mail
sendgrid.js
:touch sendgrid.js
sendgrid.js
file, add the following lines of code:const sendgrid = require('@sendgrid/mail');
const SENDGRID_API_KEY = "<SENDGRID_API_KEY>"
sendgrid.setApiKey(SENDGRID_API_KEY)
const msg = {
to: '[email protected]',
// Change to your recipient
from: '[email protected]',
// Change to your verified sender
subject: 'Sending with SendGrid Is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
}
sendgrid
.send(msg)
.then((resp) => {
console.log('Email sent\n', resp)
})
.catch((error) => {
console.error(error)
})
SENDGRID_API_KEY
with the SendGrid API key you created previously and make sure the email address in the From field has been verified by SendGrid. You can do this by creating a sender identity. This verifies that the email address actually belongs to you. Also, replace the email address in the To field from [email protected]
to your test recipient.node sendgrid.js
@trycourier/courier
. To install it, run:npm install @trycourier/courier
courier.js
:touch courier.js
const { CourierClient } = require("@trycourier/courier");
const courier = CourierClient({ authorizationToken: "<AUTH_TOKEN>" });
courier.send({
eventId: "<EVENT ID>", *// your Notification ID
recipientId: "<RECIPIENT_ID", *// usually your system's User ID
profile: {
email: "<EMAIL_ADDRESS>"
},
data: {} *// optional variables for merging into templates }).then((resp) => {
console.log('Email sent', resp)
})
.catch((error) => {
console.error(error)
});
email
refers to the email address of the recipient.