Skip to content

Instantly share code, notes, and snippets.

@archiewood
Created January 30, 2025 19:09
Show Gist options
  • Save archiewood/1dae21aca89219b456e3393334edf554 to your computer and use it in GitHub Desktop.
Save archiewood/1dae21aca89219b456e3393334edf554 to your computer and use it in GitHub Desktop.
Send an email with an attached pdf
import nodemailer from 'nodemailer';
import * as dotenv from 'dotenv';
import fs from 'fs';
// Load environment variables
dotenv.config();
const sendEmail = async () => {
try {
// Read recipients and email content from .env
const emailList = (process.env.EMAIL_LIST || '').split(',');
const subject = process.env.EMAIL_SUBJECT || 'Your PDF is ready!';
const text = process.env.EMAIL_BODY || 'Please find the attached PDF.';
if (!emailList.length || !emailList[0]) {
console.error('No recipients found in EMAIL_LIST.');
process.exit(1);
}
// Create transporter using SMTP or SendGrid
const transporter = nodemailer.createTransport({
service: 'SendGrid', // Use your email service provider
auth: {
user: 'apikey', // For SendGrid, the username is 'apikey'
pass: process.env.SENDGRID_API_KEY, // Your SendGrid API Key
},
});
// Read the PDF file
const pdfBuffer = fs.readFileSync('report.pdf');
// Configure email options
const mailOptions = {
from: process.env.EMAIL_FROM || '[email protected]', // Sender address
to: emailList, // Recipient list
subject: subject,
text: text,
attachments: [
{
filename: 'report.pdf',
content: pdfBuffer,
},
],
};
// Send the email
const info = await transporter.sendMail(mailOptions);
console.log(`Email sent successfully: ${info.response}`);
} catch (error) {
console.error('Error sending email:', error);
process.exit(1);
}
};
sendEmail();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment