I work for Akkio, where I'm building out a no-code predictive AI platform. If you're looking to harness the power of AI without needing a data scientist, give us a try!
Prerequisites
You'll need a few things:
-
nodemailer
, an npm package for sending email. Install it withnpm install nodemailer
. - A SMTP provider set up. I personally use Zoho's $12/yr plan, but any SMTP provider out there should work.
The Code
We first put the SMTP credentials in a .env
file, which we'll use to access them in our code. With Zoho, it's likely easiest to just use your main account login details here.
EMAIL = <put your email here>
PASSWORD = <put your password here>
We then import dotenv
and nodemailer
and use it's createTransport function to create a transporter object. We pass in the SMTP credentials as an object.
import dotenv from 'dotenv'
import nodemailer from 'nodemailer'
const mailTransport = nodemailer.createTransport({
host: 'smtp.zoho.com',
port: 465,
secure: true,
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD,
},
})
Note that I'm using import
instead of require
here. This is because I'm using ES Modules, which is the (not so new, at this point) standard for JavaScript. You can read more about it here.
Next, we define whatever HTML we're trying to send:
let html = ''
let name = 'John Doe'
html += `<div>Hello <span style="color: blue">${name}</span>! This is HTML that you can do whatever with. You can use template strings to make it easier to write.</div>
After this, we can use the sendMail
function to send an email. We pass in an object with the email's details.
import { format } from 'date-fns'
const mailOptions = {
from: process.env.EMAIL,
to: emailAddress,
subject: `Newsletter - ${format(new Date(), 'MMM d')}`,
html: content,
}
mailTransport.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error)
} else {
console.log(`Email successfully sent to ${emailAddress}.`)
}
})
A few notes:
- If you aren't using Zoho, most providers' SMTP details are well-documented. Note that free providers like Gmail have checks against some kinds of automated use which make this kind of thing more difficult. I recommend just getting a cheap provider like Zoho.
- The
sendMail
function has atext
option as well, which lets you send just pure text.
Conclusion
Hope you learned something! You can check out my other blog posts at https://andenacitelli.com.
Top comments (0)