【问题标题】:Sending Email from Angular 2从 Angular 2 发送电子邮件
【发布时间】:2017-08-28 19:12:25
【问题描述】:

如何从 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>

这是我的联系表单组件:

// 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 中的代码。

任何帮助将不胜感激。感谢您的宝贵时间!

【问题讨论】:

  • 我以前在 Angular 2 中做过这个,我会看看我是怎么做的。

标签: node.js angular email firebase


【解决方案1】:

尝试将您的 sendmail.js 重写为 rest 服务,例如:

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);
  });
}

请注意,我在电子邮件正文中使用了表单数据

然后在你的提交函数中,只需执行

http.post('http://localhost:3000/send-mail', this.contactForm.value);

【讨论】:

    【解决方案2】:

    编辑: 我刚刚看到您在 Firebase 上提供服务,我将研究这会如何改变事情。

    How would I run server-side code in Firebase?

    Angular 2 是客户端,如果您想使用您的秘密进行 API 调用,您可能应该在服务器端进行,也就是 node.js 或任何您的服务器。

    因为您有 sendmail.js 作为脚本,请考虑使用 node.js 为您的 Angular 2 应用程序提供服务,并使用 express 提供 API 端点,例如 /api/sendMail,您可以从您的 Angular 2 应用程序发出 XHR/AJAX 请求.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 2018-06-09
      相关资源
      最近更新 更多