Shalom Mathew
Shalom Mathew

Reputation: 295

How to create an api that sends mails using node and mongodb

Am trying to create an app that sends mails. It gets the user input(To, Subject, Message) onClick of the form button sends a mail, and store that mail on mongodb

front end

<form>
<span>
to :<input type='text' >
</span>

cc :<input type='text' >
</span>

bcc :<input type='text' >
</span>

<span>
subject :<input type='text' >
</span>

<span>
message :<input type='text' >
</span>
</form>

Back end

to = '[email protected]',
cc = '[email protected]',
bcc = '[email protected]',
subject = 'A project proposal',
message = 'the body of your mail',
etc...
  1. Schema

    const mongoose = require('mongoose');

    const UserSchema = new mongoose.Schema({

    to: { type: String, }, cc: { type: String, }, bcc: { type: String, }, bcc: { type: String, }, subject: { type: String, }, message: { type: String, }, attachment: { type: String, }, date: { type: Date, default: Date.now },

    });

    const Mail = mongoose.model('Mail', UserSchema);

    module.exports = Mail;

A.p.i

const Mail = require('../models/Mail');

// Home Page
router.get('/', forwardAuthenticated, (req, res) => res.render('home'));

// Mail
router.get('/mail', ensureAuthenticated, (req, res) =>
  res.render('mail', {
    user: req.user,
    mail: req.mail

  })
);

router.post('/mail', (req, res) => {
  const { to, cc, bcc, subject, message, attachment, account } = req.body;
  let errors = [];

  if (!name || !subject || !message || !account) {
    errors.push({ msg: 'Please enter all fields' });
  }

  if (errors.length > 0) {
    res.render('register', {
      errors,
      name,
      subject,
      message,
      account
    });
  } else {
    const newMail = new Mail({
      to,
      cc,
      bcc,
      subject,
      message,
      attachment,
      account
    });

    newMail
      .save()
      .then(mail => {
        req.flash(
          'success_msg',
          'mail sent'
        );

      })
      .catch(err => console.log(err));

  }
})
module.exports = router;

how do i go about it here?

Upvotes: 1

Views: 4269

Answers (2)

Rajneshwar Singh
Rajneshwar Singh

Reputation: 122

Try express-mailer for sending an email. In this, you can also send an email in CC and Bcc by a comma-separated list or an array. Please check express-mailer documentation carefully.

var app = require('express')(),
var mailer = require('express-mailer')

mailer.extend(app, {
    emailFrom: "[email protected]", 
    host: 'smtp.gmail.com', // hostname
    secureConnection: true, // use SSL
    port: 465, // port for secure SMTP
    transportMethod: 'SMTP', // default is SMTP.
    auth: {
        user: '[email protected]', // Your Email 
        pass: '*******' // Your Password
    }
});

app.mailer.send('../views/emailTemplate/emailTemplate.ejs', { to: '[email protected]', subject: 'Your Email Subject'}, function (err, message) {
    if (err) throw new Error(err);
    console.log(message);
    return;
});

Upvotes: 1

Denis
Denis

Reputation: 104

I use 'nodemailer' module, you can just read their documentation, but i show you a simple example:

var nodemailer = require ('nodemailer');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var transporter = nodemailer.createTransport ({ 
    service: 'gmail', 
    auth: { 
            user: '[email protected]', 
            pass: 'yourePassword' 
        } 
    });

 module.exports={
     sendAUTH:function(link, email){
        const mailOptions = { 
            from: '[email protected]',  
            to: email,  
            subject: 'Subject of your email', 
            html: `<a href='`+link+`'>link</a>` 
          };
          transporter.sendMail (mailOptions, function (err, info) { 
            if (err) 
              console.log (err) 
            else 
              console.log (info); 
         });
     }
 }

Upvotes: 3

Related Questions