简体   繁体   中英

node-mandrill sending mail via server

this is a newbie question on using node-mandrill properly and most probably on node itself as I am still trying to learn it. But since I have seen many examples to use the api key of mandrill directly from the client side and therefore revealing it, I was wondering how exactly it was working when served but got stuck at this point:

I have an app.js serving a public folder...

app.js

var express = require('express');
var mandrill = require('node-mandrill')(API_KEY); 
var app = express();
app.use(express.static('public'));
app.listen(PORT);

function sendEmail ( _name, _email, _subject, _message) {
    mandrill('/messages/send', {
        message: {
            to: 'EMAIL',
            from: [{email: _email , name: _name}],
            subject: _subject,
            text: _message
        }
    }, function(error, response){
        if (error) console.log( error );
        else console.log(response);
    });
}

...where a client script is used to collect info from a contact form and send an email upon clicking a submit button.

form.js

var contactForm = document.getElementById( 'contactForm' );
            new stepsForm( contactForm, {
                onSubmit : function( form ) {

                    // send email
                    var _subject = 'Contact Request';
                    var _email = contactForm.elements['q4'].value;
                    var _name = contactForm.elements['q5'].value;
                    var _message = contactForm.elements['q6'].value;

                    sendEmail(_name,_email,_subject,_message);

                }
            } );

Could you please tell me what's missing/wrong? Thanks.

You can't call your back-end function from client. You can use Jquery to make Ajax call like:

$(document).ready(function(){

      $('#contactForm').submit(function(event) {
        event.preventDefault();
        var _subject = 'Contact Request';
        var _email = contactForm.elements['q4'].value;
        var _name = contactForm.elements['q5'].value;
        var _message = contactForm.elements['q6'].value;

        $.ajax({
          url: '/sendEmail',
          method: 'post',
          contentType: 'application/json',
          data: JSON.stringify({ subject: _subject, email: _email}),
          success: function(res) {

          }
        })

      })

})

And in your back-end:

// some lines skipped

app.post('/sendEmail', function(req, res) {

     //do your stuff
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM