falcon25
falcon25

Reputation: 11

Sending an email to user in JavaScript + Node.js (nodemailer?)

I've created a shopping React app and I want to send the user an approval mail after he clicked the purchase button. I've researched but couldn't find the way to do so. I've tried nodemailer bu it only let's you send an email to yourself (meaning a pre-specified address in the code)

Anyone knows a package/method to do it?

Edit : This is the answer using nodemailer -

IMPORTANT - if you want to use Gmail as the sender account, you need to enable use of less safe applications in your Gmail account via this link : https://myaccount.google.com/lesssecureapps

        const transporter = nodemailer.createTransport({
        service : 'gmail',
        auth: {
            user: 'YOUR_MAIL_ADDRESS',
            pass: 'YOUR_MAIL_PASSWORD'
        },
        tls:{
            rejectUnauthorized:false
          }
    });

    let mailOptions = {
        to: "RECIPIENT_MAIL_ADDRESS",
        subject: 'Node Contact Request', // Subject line
        text: 'Hello world?', // plain text body
        html: htmlMail // html body
    };


    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);   

    });

Upvotes: 0

Views: 570

Answers (1)

Dharmendra Vaishnav
Dharmendra Vaishnav

Reputation: 305

Using Nodemailer

let useEmail ="[email protected]"
let info = await transporter.sendMail({
    from: '"Fred Foo 👻" <[email protected]>', // sender address
    to: userEmail, // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world?", // plain text body
    html: "<b>Hello world?</b>" // html body
  });

Here, "to" is just a string.

You can take user's email, you would have stored it somewhere in your code(Redux or AsyncStorage or would have taken user Input) and use it in the to field.

Upvotes: 1

Related Questions