AndrewLeonardi
AndrewLeonardi

Reputation: 3512

NodeMailer - No recipients defined error

I'm trying to send an email using Node mailer. My set up is below. The recipient comes from a Mongoose model. In the Model Rentals.createdbyemail contains the email address of the user. I've double checked to make sure the email address is contained within Rentals.createdbyemail and it is.

For some reason when this code runs I get an error:

Error: No recipients defined

How would I change my code to correct this error? Thanks for any help!
Note: It works if I just enter an email address for the "to" field.

 var smtpTrans = nodemailer.createTransport({
       service: 'Gmail',
        auth: {
            user: '[email protected]',
            pass: 'password'
        }
      });
      var mailOptions = {
        to: Rentals.createdbyemail,
        from: 'email',
        subject: 'subject',
        text: 'This is the email content'
      };
      smtpTrans.sendMail(mailOptions, function(err) {
        console.log('email sent')

        if (err){
        console.log(err)
        }
      });

The recipient is coming from a mongoose model:

var rentalsSchema = new mongoose.Schema({
   reserved: {type: Boolean, default: false},
   createdby: String,
   createdbyemail: String,
   reservedby: String,
   reservedemail: String,
   author: {
      id:{
       type: mongoose.Schema.Types.ObjectId,
       ref: "User"
      },
       username: String,
       email: String
   },

module.exports = mongoose.model("Rentals", rentalsSchema);

Upvotes: 0

Views: 8111

Answers (1)

Shaishab Roy
Shaishab Roy

Reputation: 16805

In your code missing to assign recipient email because you used Rentals.createdbyemail that's not a valid way to assign. So you should retrieve createdbyemail from database and then used retrieve email.

I don't know from where you want to send email (means which function or how to retrieve from db). so I am showing how to retrieve and send email

like:

Retrieve the email from Rentals table

// {field: value} to get specific Rental
Rentals.findOne({field: value}, function(err, rental) {
 if(rental) {
   var smtpTrans = nodemailer.createTransport({
       service: 'Gmail',
        auth: {
            user: '[email protected]',
            pass: 'password'
        }
      });
      var mailOptions = {
        to: rental.createdbyemail,
        from: 'email',
        subject: 'subject',
        text: 'This is the email content'
      };
      smtpTrans.sendMail(mailOptions, function(err) {
        console.log('email sent')

        if (err){
        console.log(err)
        } else {
           return from here 
        }
      });
 }
});

Upvotes: 1

Related Questions