Sending AngularJS form to NodeMailer to send email

可紊 提交于 2019-12-01 22:59:59

At the node side you can create a REST end point in order to recieve a POST request from the server for the form submission of email in the modal box. The REST end-point will look like this if you have an express server.

var express = require('express');
var router = express.Router();
var app = express();
app.post('/postEmail',function(req,res){
    //Your NodeMailer logic comes here
});

In the angular part, just like you have written a service, you can create an angular factory to invoke this REST end point.

For example:

myApp.factory('postEmailForm',['$http',function($http){
   return {
     postEmail: function(emailData,callback){
       $http.post("/postEmail/", emailData).success(callback);  
     }
   }
}]);

where myApp is your angular module, emailData is the emailForm data which you want to send to the server (it will be posted in the body of the request)

Angular code:

angular.module('sendmailApp', [])
.controller('MailController', function ($scope,$http) {
    $scope.loading = false;
    $scope.send = function (mail){
        $scope.loading = true;
        $http.post('/sendemail', {
            to: mail.to,
            subject: 'Message from AngularCode',
            text: mail.message
        }).then(res=>{
            $scope.loading = false;
            $scope.serverMessage = 'Email sent successfully';
        });
    }

})

Node.js code:

let express = require('express'),
app = express(),
bodyParser = require('body-parser'),
nodemailer = require("nodemailer"),
server = require('http').Server(app);

const OTP_EMAIL_CONFIG= {     
"host": 'smtp.gmail.com',     
"port": 465,     
"secure": true,     
"auth": {         
"user": 'enter gmail account',         
"pass": 'gmail password...'     
} };

let mailModule = nodemailer.createTransport(OTP_EMAIL_CONFIG);
app.use(express.static(__dirname + '/client'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/',function(req,res){
    res.send('hello world!');
}) // Method to send email....
app.post('/sendemail',function(req,res){
    console.log(req.body,'request');
     var mailOptions = {
        from: '"jsonworld " enter gmail account which you want to use for sending email',         
to: req.body.to,         
subject: "mail sending with angularjs and nodejs",  
       text: "Congratulations! mail is sending properly now."     
};     
mailModule.sendMail(mailOptions);     
res.status(200).send('Mail sent successfully'); })
server.listen(3003,function(){ console.log('server listening on port: 3003'); });

For getting working demo go here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!