Angular.js and Angular-material comment form sent to inbox with nodemailer

Connect comment form to personal email inbox using $mdPanel

It is easy to set up email functionality from an app. By installing a couple of NPM modules such as nodemailer you can have comments sent to your inbox with a few lines of code. Nodemailer and sendgrid do all the heavy lifting here making setting up complicated server calls to send emails a piece of cake.
  • Inside the app run command npm install nodemailer body-parser nodemailer-sendgrid-transport --save. This will install the packages needed to send comments to email and the packages will save to the package.json.
  • Require the modules in the server.js file. Set up body-parser and nodemailer transport function. The nodemailer module will require node.js version 6.0.0 or higher. To upgrade your node.js version on your machine you can use this node version manager https://github.com/tj/n.
var express = require('express');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var sgTransport = require('nodemailer-sendgrid-transport');
var app = express();

// set the port of our application
// process.env.PORT lets the port be set by Heroku
var port = process.env.PORT || 8082;

// make express look in the public directory for assets (css/js/img)
app.use(express.static(__dirname + '/client/app'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// set the home page route
app.get('/', function(req, res) {

    // make sure index is in the right directory. In this case /app/index.html
    res.render('index');
});

// Send comment route
app.post('/sendmail', function(req, res){
    var options = {
        auth: {

            sendgrid_api_key: 'SG.fakekey123412341234xp1234123xp12341234xxxx1234fakekey'

        }
    }

    var mailer = nodemailer.createTransport(sgTransport(options));
    mailer.sendMail(req.body, function(error, info){

        if(error){
            res.status('401').json({err: info});
        }else{
            res.status('200').json({success: true});
        }
    });
});


app.listen(port, function() {
    console.log('Our app is running on http://localhost:' + port);
});

- Warning: Don't push sendgrid api key to public github repo. Use the api key for local development and testing only.
  • Get an api key from a free personal sendgrid account. To get the key aproval is needed from sendgrid. Setting up sendgrid as heroku plugin and then getting the sendgrid key from the sendgrid dashboard of the heroku app is the way to get around approval. Reference: Heroku sendgrid add-on. It should be a one click install to a specified heroku app then access the sendgrid dashboard and access the api key there.

  • Make a call to the server.js function from the client with this html and function from a angular controller. Use $http angular service as a controller dependency to call to server.js with comment data and send the comment text to a specific email inbox. Use this html in an Angular Material service called $mdPanel.

<!-- make function call to the controller to open the panel from comment.html -->
<md-button class="md-fab comment" aria-label="Comment" ng-click="comCtrl.showPanel($event)">
        <md-icon md-svg-icon="comment"></md-icon>
</md-button>
<!-- comment-panel.html -->
<md-toolbar layout="row">
    <h2 class="md-toolbar-tools">Send a comment</h2><span flex></span>
    <div class="close-icon">
        <md-icon md-svg-icon="close" ng-click="vm.closeDialog()"></md-icon>
    </div>
</md-toolbar>
<md-content layout-padding>
    <form name="commentForm">
        <!-- Prevent comment textarea from overflow with wrapper -->
        <div class="wrapper">
            <div layout="row" layout-sm="column" layout-align="space-around" ng-if="vm.isLoading">
                <md-progress-circular md-mode="indeterminate"></md-progress-circular>
            </div>
            <md-input-container class="md-block" ng-if="!vm.isLoading">
                <label for="">Comment</label>
                <textarea type="text" ng-model="vm.mail.comment" md-maxlength="2000" name="comment" rows="4" required></textarea>
                <div ng-messages="commentForm.comment.$error" ng-if="commentForm.comment.$dirty">
                    <div ng-message="required" class="my-messages" role="alert">This field is required.</div>
                    <div ng-message="md-maxlength" class="my-messages" role="alert">Message must not exceed 2000 characters.</div>
                </div>
            </md-input-container>
        </div>
        <md-button class="md-raised md-button md-ink-ripple md-send" ng-click="vm.sendComment(vm.mail)" ng-disabled="commentForm.$invalid">Send</md-button>
    </form>
</md-content>
       //comment-directive.js

        var self = this;

        self.showPanel = showPanel;

        function showPanel($event) {

            var position = $mdPanel.newPanelPosition()
                .absolute()
                .left('50%')
                .top('50%');


            var config = {
                attachTo: angular.element(document.body),
                controller: PanelDialogCtrl,
                controllerAs: 'vm',
                disableParentScroll: this.disableParentScroll,
                templateUrl: 'components/comment/comment-panel.html',
                hasBackdrop: true,
                panelClass: 'comment',
                position: position,
                trapFocus: true,
                zIndex: 150,
                clickOutsideToClose: true,
                escapeToClose: true,
                focusOnOpen: true
            };

            $mdPanel.open(config);
        };

function PanelDialogCtrl(mdPanelRef) {
var self = this;

self.sendComment = sendComment;
self.mail = null;
self.serverMessage = null;
self.isLoading = false;
self.mdPanel = mdPanelRef;
self.closeDialog = closeDialog;


function sendComment(mail) {

    self.mail = mail;
    self.isLoading = true;

    // SENDING COMMENT TO THE SERVER
    $http.post('/sendmail', {
        from: 'person <email@inbox.com>',
        to: 'email@inbox.com',
        subject: 'Comment from MyApp',
        text: self.mail.comment
    }).then(res => {
        self.isLoading = false;
        self.serverMessage = 'Your comment was sent successfully.';

    });

}

function closeDialog() {
      self.mdPanel.close();
    }
}
  • Install angular-messages to make validations messages work run bower install angular-messages --save. Add ngMessages to the ng-app module angular.module('MyApp', ['ngMessages'])

  • Enter an inbox that you have access to and send a comment to test.

Check the codebase on my GitHub account!