8

How Do I Send Email from an Angular 2 App?

I am hosting an Angular 2 app on firebase. I want to send a contact form as an email. Ideally my solution would use Nodejs, but I am willing to use anything that will get the job done properly. Below is a breakdown of my app.


Client Side Progress

Here is my form:

<!-- contact-form.component.html -->

<form [formGroup]="formService.contactForm" (ngSubmit)="formService.onSubmitForm()">

  <input type="text" formControlName="userFirstName">
  <label>First Name</label>
  
  <input type="text" formControlName="userLastName">
  <label>Last Name</label>

  <button type="submit">SUBMIT</button>
  
</form>

Here is my contact-form component:

// contact-form.component.ts
import { Component } from '@angular/core';

import { ContactFormService } from './contact-form.service';

@Component({
  selector: 'contact-form',
  templateUrl: './contact-form.component.html',
  styleUrls: ['./contact-content.component.css'],
  providers: [ContactFormService]
})
export class ContactFormComponent {

  constructor(private formService: ContactFormService) {
    formService.buildForm();
  }

}

Here is my contact-form service:

// contact-form.service.ts

import { Injectable } from '@angular/core';

import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';


@Injectable()
export class ContactFormService {

  constructor(public formBuilder: FormBuilder) { }

  contactForm: FormGroup;
  formSubmitted: boolean = false;


  buildForm() {
    this.contactForm = this.formBuilder.group({
      userFirstName: this.formBuilder.control(null, Validators.required),
      userLastName: this.formBuilder.control(null, Validators.required)
    });
  }

  onSubmitForm() {
    console.log(this.contactForm.value);
    this.formSubmitted = true;
    this.contactForm.reset();
  }

}

When I click the submit button, the form data will successfully display in the console.


Server-Side Nodejs Progress

I can successfully send emails from the command prompt using SendGrid and Nodejs:

Example: sendmail.js

var Sendgrid = require('sendgrid')(
  process.env.SENDGRID_API_KEY || '<my-api-key-placed-here>'
);

var request = Sendgrid.emptyRequest({
  method: 'POST',
  path: '/v3/mail/send',
  body: {
    personalizations: [{
      to: [{ email: 'my.email@gmail.com' }],
      subject: 'Sendgrid test email from Node.js'
    }],
    from: { email: 'noreply@email-app.firebaseapp.com' },
    content: [{
      type: 'text/plain',
      value: 'Hello Joe! Can you hear me Joe?.'
    }]
  }
});

Sendgrid.API(request, function (error, response) {
  if (error) {
    console.log('Mail not sent; see error message below.');
  } else {
    console.log('Mail sent successfully!');
  }
  console.log(response);
});

And then an email will successfully send if I type this in the command prompt:

node sendmail

However, I cannot figure out how to link my submitted form data to sendmail.js and also I cannot figure out how to activate the code in sendmail.js by clicking the submit button.

Any help would be greatly appreciated. Thanks for your time!

Community
  • 1
  • 1
Ty Sabs
  • 209
  • 1
  • 2
  • 10

2 Answers2

3

try to rewrite your sendmail.js as rest service, for example:

const Sendgrid = require('sendgrid')(
  process.env.SENDGRID_API_KEY || '<my-api-key-placed-here>'
);

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/send-mail', function (req, res) {
  // PUT your send mail logic here, req.body should have your fsubmitted form's values
  sendMail(req.body);
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.send('SEND MAIL');  
})

app.listen(3000, function () {
  console.log('LISTENING on port 3000');
})


function sendMail(formData) { 
  let request = Sendgrid.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: {
      personalizations: [{
        to: [{ email: 'my.email@gmail.com' }],
        subject: 'Sendgrid test email from Node.js'
      }],
      from: { email: 'noreply@email-app.firebaseapp.com' },
      content: [{
        type: 'text/plain',
        value: `Hello ${formData.userFirstName} ${formData.userLastName}! Can you hear me ${formData.userFirstName}?.` 
      }]
    }
  });

  Sendgrid.API(request, function (error, response) {
    if (error) {
      console.log('Mail not sent; see error message below.');
    } else {
      console.log('Mail sent successfully!');
    }
    console.log(response);
  });
}

please note, that I used form data within email's body

then in your submit function in angular, just execute

http.post('http://localhost:3000/send-mail', this.contactForm.value);
Andriy
  • 14,781
  • 4
  • 46
  • 50
1

Edit: I just saw that you are serving on Firebase, I will look into how that changes things.

How would I run server-side code in Firebase?

Angular 2 is client side, if you want to do make an API call w/ your secret you should probably be doing it server side, aka node.js or whatever your server is.

Because you have sendmail.js as a script, consider serving your Angular 2 application with node.js and having an API endpoint with express, like /api/sendMail that you can make an XHR/AJAX request to from your Angular 2 application.

Community
  • 1
  • 1
Jim Factor
  • 1,465
  • 1
  • 15
  • 24