Sending Email with Node Mailer and Sendgrid in Angular MEAN stack using angular-fullstack from Yeoman

后端 未结 1 890
故里飘歌
故里飘歌 2021-01-06 15:22

I am trying to understand where to locate the logic to send an email via a contact form in my Angular App (using angular-fullstack MEAN stack from Yeoman).

I can add

1条回答
  •  盖世英雄少女心
    2021-01-06 15:36

    You need to create a route on the server that you can post form values to from Angular using $http.post. The following lets you enter details in an Angular form. The form is then posted to Node where the req.body values are extracted and added email object. The email is then send by SendGrid.

    SERVER.JS

    var express = require('express');
    var http = require('http');
    var bodyParser = require('body-parser');
    var dotenv = require('dotenv'); 
    
    dotenv.load(); //load environment variables from .env into ENV (process.env).
    
    var sendgrid_username   = process.env.SENDGRID_USERNAME;
    var sendgrid_password   = process.env.SENDGRID_PASSWORD;
    
    var sendgrid   = require('sendgrid')(sendgrid_username, sendgrid_password);
    var email      = new sendgrid.Email();
    
    var app = express();
    app.use(bodyParser.json()); //needed for req.body
    app.set('port', process.env.PORT || 3000);
    app.use(express.static(__dirname + '/public')); 
    
    app.post('/email', function(req, res) {
        email.addTo(req.body.to);
        email.setFrom(req.body.from);
        email.setSubject(req.body.subject);
        email.setText(req.body.text);
        email.addHeader('X-Sent-Using', 'SendGrid-API');
        email.addHeader('X-Transport', 'web');
    
        sendgrid.send(email, function(err, json) {
        if (err) { 
            return res.send("Problem Sending Email!!!!");
        }
            console.log(json);
            res.send("Email Sent OK!!!!");
        });
    });
    var server = http.createServer(app);
    server.listen(app.get('port'), function() {
      console.log('Express server listening on port ' + app.get('port')  ) ;
    });
    

    INDEX.HTML

    
    
    
        
        
        
    
    
        

    CLIENT SIDE APP.JS

    angular.module('myApp', [])
    
    .controller('MainCtrl', function($scope, $http) {
    
            $scope.submitEmail = function() {
    
                console.log("TEST");
            //Request
            $http.post('/email', $scope.email) 
            .success(function(data, status) {
                console.log("Sent ok");
            })
            .error(function(data, status) {
                console.log("Error");
            })
        };
    });
    

    0 讨论(0)
提交回复
热议问题