简体   繁体   English

使用来自Yeoman的angular-fullstack在Angular MEAN堆栈中使用Node Mailer和Sendgrid发送电子邮件

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

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). 我试图了解在我的Angular App中通过联系表单发送电子邮件的逻辑位置(使用Yeoman的angular-fullstack MEAN堆栈)。

I can add the logic to send an email in the app.js file on the server side using nodemailer and sendgrid and everything works and an email is sent every time I refresh the server, however I am a little fuzzy on where to place the logic so that it only gets sent once the form is submitted and it hits the server side. 我可以添加逻辑,使用nodemailer和sendgrid在服务器端的app.js文件中发送电子邮件,一切正常,每次刷新服务器时都会发送一封电子邮件,不过我在哪里放置逻辑有点模糊这样只有在提交表单后它才会被发送,并且它会到达服务器端。

This is what the create action looks like on the Express JS side... 这就是Express JS方面的创建动作......

 exports.create = function(req, res) { Contact.create(req.body, function(err, contact) { if(err) { return handleError(res, err); } return res.json(201, contact); }); }; 

Here is the code in app.js that is working, but obviously not in the right place... 以下是app.js中正在运行的代码,但显然不在正确的位置......

 var nodemailer = require('nodemailer'); var sgTransport = require('nodemailer-sendgrid-transport'); var options = { auth: { api_user: 'username', // 'SENDGRID_USERNAME' - Recommended to store as evn variables api_key: 'password', // 'SENDGRID_PASSWORD' } }; var mailer = nodemailer.createTransport(sgTransport(options)); var email = { to: 'sendto@email.com', from: 'sendfrom@email.com', subject: 'Test Email', text: 'Awesome Email', html: '<b>Bold and Awesome Email</b>' }; mailer.sendMail(email, function(err, res) { if (err) { console.log(err) } console.log(res); }); 

Coming from a rails background my initial thought is to stick the logic in the create action so that if the object is created successfully the email gets sent. 来自rails背景我最初的想法是在创建操作中粘贴逻辑,这样如果成功创建对象,则会发送电子邮件。 Is this a correct way of thinking about it in this scenario...I am new to the MEAN stack. 在这种情况下,这是一种正确的思考方式......我是MEAN堆栈的新手。

Thanks for any help... 谢谢你的帮助...

You need to create a route on the server that you can post form values to from Angular using $http.post. 您需要在服务器上创建一个路径,您可以使用$ http.post从Angular发布表单值。 The following lets you enter details in an Angular form. 以下内容允许您以Angular形式输入详细信息。 The form is then posted to Node where the req.body values are extracted and added email object. 然后将表单发布到Node,其中提取req.body值并添加电子邮件对象。 The email is then send by SendGrid. 然后由SendGrid发送电子邮件。

SERVER.JS 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 INDEX.HTML

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="utf-8">
    <title></title>
    <!-- CSS -->
</head>
<body ng-controller="MainCtrl">
    <form name="emailForm">    
        <div class="group">      
          <input type="email" name="to" ng-model="email.to" ng-required="true">
          <label>To</label>
        </div>
        <div>      
          <input type="email" name="from" ng-model="email.from" ng-required="true">
          <label>From</label>
        </div>
        <div>      
          <input type="text" name="subject" ng-model="email.subject" ng-required="true">
          <label>Subject</label>
        </div>
        <div>      
            <textarea ng-model="email.text" name="text" placeholder="Enter Text Here.."></textarea>
        </div>

        <button id="emailSubmitBn" type="submit" ng-click="submitEmail()">
            Submit
        </button>
    </form>
    <!-- JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>   
    <script type="text/javascript" src="js/app.js"></script>
</body>
</html>

CLIENT SIDE APP.JS 客户端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");
        })
    };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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