Attach file with mail in node
In Node.js, you can attach a file to an email using a library such as nodemailer
. Here's an example of how to do it:
First, install nodemailer
using npm:
npm install nodemailer
Then, create a Node.js script that sends an email with an attached file:
const nodemailer = require('nodemailer');
// create a transporter object
let transporter = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587,
secure: false, // or 'STARTTLS'
auth: {
user: '[email protected]',
pass: 'your_password'
}
});
// define the email options
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Test email with attachment',
text: 'Hello from Node.js!',
attachments: [
{
filename: 'example.txt',
path: './example.txt' // path to the file you want to attach
}
]
};
// send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Email sent: ' + info.response);
});
In this example, we create a transporter
object using nodemailer.createTransport()
and specify the SMTP server settings. We then define the email options using an object, including the from
, to
, subject
, text
, and attachments
properties.
The attachments
property is an array of objects, where each object specifies the file to attach. In this case, we're attaching a file named example.txt
located in the current working directory.
Finally, we call transporter.sendMail()
to send the email. If the email is sent successfully, the callback function will log a success message to the console.
Note that you'll need to replace the placeholders ([email protected]
, your_password
, [email protected]
, and example.txt
) with your actual email credentials and file path.