0

I'm trying to create a plugin for haraka mailserver to support saving emails to mongodb. The plugin is running fine however when I send a test email it's giving me this error:

Plugin queue/mongo_email failed: TypeError: Email.save is not a function

This is the plugin code:

var mongoose         = require('mongoose');

var mongodbUri = "mongodb://localhost:27017/";

var options = {
  useMongoClient: true,
  socketTimeoutMS: 0,
  keepAlive: true,
  reconnectTries: 30
};

var db = mongoose.connect(mongodbUri, options);

var EmailSchema = mongoose.Schema({
  emailFrom: String,
  emailMsg: String,
  emailRcv: String,
  emailSubject: String
});

var Email = mongoose.model('Email', EmailSchema);

exports.hook_queue = function(next, connection){

    var transaction   = connection.transaction;
    var receivedDate  = transaction.header.headers.date;
    var subjectLine   = transaction.header.headers.subject;

    Email.save({
      emailFrom: transaction.mail_from,
      emailMsg: transaction.data_lines,
      emailRcv: receivedDate,
      emailSubject: subjectLine
    });

    next();

}
tosi
  • 611
  • 9
  • 24
  • 1
    Thanks for wanting to show your solution. However, please do not overwrite your question with the answer - the result is that no-one will be able to understand what problem you have fixed. Instead, put your solution below, in a self-answer. You can also click the tick symbol to mark the question as resolved. – halfer Nov 28 '17 at 14:46
  • 1
    The question has been updated, thanks for your advice! – tosi Nov 28 '17 at 19:02

1 Answers1

1

Answer:

var mongoose         = require('mongoose');

var mongodbUri = "mongodb://localhost:27017/";

var options = {
  useMongoClient: true,
  socketTimeoutMS: 0,
  keepAlive: true,
  reconnectTries: 30
};

var db = mongoose.connect(mongodbUri, options);

var EmailSchema = mongoose.model('Email',{
  emailFrom: String,
  emailMsg: String,
  emailRcv: String,
  emailSubject: String
});


exports.hook_queue = function(next, connection){

    var transaction   = connection.transaction;
    var receivedDate  = transaction.header.headers.date;
    var subjectLine   = transaction.header.headers.subject;

    var Email = new EmailSchema({
      emailFrom: transaction.mail_from,
      emailMsg: transaction.data_lines,
      emailRcv: receivedDate,
      emailSubject: subjectLine
    });

    Email.save();

    next();

}

The transaction variable var transaction = connection.transaction; is an object containig all information regarding new emails. The mongodb schema EmailSchema can be modified to support other options such as message headers, attachments, etc.

tosi
  • 611
  • 9
  • 24