updated github path
[oweals/finalsclub.git] / mailer.js
1 /* vim: set ts=2: */
2
3 // Core
4 var fs  = require( 'fs' );
5
6 // Amazon
7 var aws = require( 'aws-lib' );
8
9 // Templating
10 var ejs = require( 'ejs' );
11
12 function buildPath( template ) {
13         return './emails/' + template + '.ejs';
14 }
15
16 function Mailer( accessKey, secretKey ) {
17         this.accessKey  = accessKey;
18         this.secretKey  = secretKey;
19
20         this.client                     = aws.createSESClient( this.accessKey, this.secretKey );
21 }
22         
23 module.exports = Mailer;
24
25 Mailer.prototype.send = function( msg, callback ) {
26         if( ! msg.template && ! msg.body ) {
27                 callback( new Error( 'Invalid message specification!' ) );
28         }
29
30         if( msg.template ) {
31                 var templatePath = buildPath( msg.template );
32
33                 var data = fs.readFileSync( templatePath, 'utf8' );
34
35                 msg.body = ejs.render( data, { locals: msg.locals } ); // .replace( /\\n/g, '\n' );
36         }
37
38         var params = {
39                 'Destination.ToAddresses.member.1'      : msg.to,
40                 'Message.Body.Html.Charset'                                     : 'UTF-8',
41                 'Message.Body.Html.Data'                                                : msg.body,
42                 'Message.Subject.Charset'                                               : 'UTF-8',
43                 'Message.Subject.Data'                                                  : msg.subject,
44                 'Source'                                                                                : 'FinalsClub.org <info@finalsclub.org>'
45         };
46
47         this.client.call( 'SendEmail', params, function( result ) {
48                 console.log( result );
49
50                 if( result.Error ) {
51                         callback( result.Error );
52                 } else {
53                         callback( null, result );
54                 }
55         });
56 }