How to send email from Angular 2 app?
I host an Angular 2 application on firebase. I want to send a contact form as an email. Ideally, my solution will use Nodejs, but I am ready to use everything that will allow me to do the job properly. The following is a breakdown of my application.
Client Side Progress
Here is my form:
<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>
Run codeHide result
Here is my contact form component:
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();
}
}
Run codeHide resultHere is my contact form service:
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();
}
}
Run codeHide resultWhen I click the submit button, the form data will be displayed successfully on the console.
Server Side Nodejs Stroke
I can successfully send letters from the command line 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);
});
Run codeHide resultAnd then the email will be sent successfully if I type it on the command line:
node sendmail
, sendmail.js, , sendmail.js, .
. !