2016-10-12 74 views
0

我的要求是從我的應用程序發送通知電子郵件到任何電子郵件ID,例如:一個Gmail地址。我經歷了一些模塊,如smtp-serversmtp-connectionemailjs如何創建一個自定義smtp服務器來發送Nodejs中的通知電子郵件?

這是我到現在爲止。

var SMTPServer = require('smtp-server').SMTPServer 

var server = new SMTPServer({ 
    name: 'testDomain.com', 
    authOptional: true, 
    onAuth: function (auth, session, callback) { 
    callback(null, {user: 'sample-user'}) 
    } 
}) 
server.on('error', function (err) { 
    console.log('Error %s', err.message) 
}) 

var port = 1234 

server.listen(port, function() { 
    console.log('SERVER: Listening on port: ' + port) 
    var opts = { 
    host: '127.0.0.1', 
    port: port, 
    username: 'testUser', 
    password: 'testUser123', 
    to: '[email protected]' 
    } 
    sendEmail(opts,function (err, message) { 
    server.close() 
    }) 
}) 

其中sendEmail是一個使用emailjs的函數。

function sendEmail(opts,callback) { 
    var server = email.server.connect({ 
    user: opts.username || '', 
    password: opts.password || '', 
    host: opts.host, 
    ssl: false 
    }) 

    server.send({ 
    text: 'i hope this works', 
    from: 'you <'+opts.username+'@testDomain.com>', 
    to: ' <'+opts.to+'>', 
    subject: 'testing emailjs' 
    }, function (err, message) { 
    console.log(err || message); 
    callback(err, message) 
    }) 
} 

但似乎客戶端無法連接到服務器。它掛着。

我試圖SMTP連接這樣開始:

var connection = new SMTPConnection({ 
    port: port, 
    host: '127.0.0.1', 
    ignoreTLS: true 
    }) 

    connection.connect(function() { 
    var envelope = { 
     from: opts.username+'@testDomain.com', 
     to: opts.to 
    } 
    var message = "Hello!!!" 
    connection.send(envelope, message, function(err,message){ 
     callback(err,message) 
     connection.quit() 

    }) 

這似乎是工作,但給出了這樣的輸出

response: '250 OK: message queued' 

的SMTP連接文件說,它只是隊列中的郵件犯規交付給收件人。

我該如何達到我的要求?我試圖從自定義郵件服務器發送通知,因爲我想避免以明文形式在代碼中添加電子郵件帳戶的用戶憑據。我正在尋找一個簡單的郵件服務器,當通知需要發送然後關閉時,郵件服務器可以啓動。

我完全偏離軌道,不理解郵件服務器的工作原理?請給出一些反饋意見和最好的方法來解決這個問題。

回答

0

只是我的意見,但我認爲它更好地採取單獨的郵件服務器。 像例如,從nodemailer

var nodemailer = require('nodemailer'); 

// create reusable transporter object using the default SMTP transport 
var transporter = nodemailer.createTransport('smtps://user%40gmail.com:[email protected]'); 

// setup e-mail data with unicode symbols 
var mailOptions = { 
    from: '"Fred Foo ?" <[email protected]>', // sender address 
    to: '[email protected], [email protected]', // list of receivers 
    subject: 'Hello ✔', // Subject line 
    text: 'Hello world ?', // plaintext body 
    html: '<b>Hello world ?</b>' // html body 
}; 

// send mail with defined transport object 
transporter.sendMail(mailOptions, function(error, info){ 
    if(error){ 
     return console.log(error); 
    } 
    console.log('Message sent: ' + info.response); 
}); 

對於安全性:

  • 您可以使用單獨的文件存儲的用戶名/密碼。

  • 使用可以使用基於令牌的認證。所以你不需要保存密碼。 OAuth就是一個例子。而不是使用令牌進行身份驗證的密碼。這個令牌是從郵件服務器提供者(例如gmail)獲得的。 使用oauth和nodemailer的示例可以找到here

相關問題