如何从Angular 2应用程序发送电子邮件?
我正在Firebase上托管一个Angular 2应用程序。我想将联系表单作为电子邮件发送。理想情况下,我的解决方案将使用Nodejs,但我愿意使用任何可以正确完成工作的东西。以下是我的应用程序概述。
客户端进度
这是我的表单:
<!-- 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>
以下是相关的IT技术内容:
// 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();
}
}
// 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();
}
}
当我点击提交按钮时,表单数据将成功显示在控制台中。
服务器端 Nodejs 进展
我可以使用 SendGrid 和 Nodejs 成功地从命令提示符发送电子邮件:
例如: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);
});
如果我在命令提示符中输入以下内容,邮件将成功发送:
node sendmail
然而,我无法弄清如何将我的提交表单数据链接到sendmail.js,并且也无法弄清如何通过点击提交按钮来激活sendmail.js中的代码。
如果有任何帮助,将不胜感激。谢谢您的时间!