node.js 从 Angular 2 发送电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43192772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:08:37  来源:igfitidea点击:

Sending Email from Angular 2

node.jsangularemailfirebase

提问by Ty Sabs

How Do I Send Email from an Angular 2 App?

如何从 Angular 2 应用程序发送电子邮件?

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.

我在 firebase 上托管了一个 Angular 2 应用程序。我想以电子邮件形式发送联系表格。理想情况下,我的解决方案将使用 Nodejs,但我愿意使用任何可以正确完成工作的东西。以下是我的应用程序的细分。



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

服务端 Nodejs 进展

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

我可以使用 SendGrid 和 Nodejs 从命令提示符成功发送电子邮件:

Example: sendmail.js

示例: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: '[email protected]' }],
      subject: 'Sendgrid test email from Node.js'
    }],
    from: { email: '[email protected]' },
    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.

但是,我无法弄清楚如何将我提交的表单数据链接到 sendmail.js,也无法弄清楚如何通过单击提交按钮来激活 sendmail.js 中的代码。

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

任何帮助将不胜感激。谢谢你的时间!

回答by Andriy

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

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

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: '[email protected]' }],
        subject: 'Sendgrid test email from Node.js'
      }],
      from: { email: '[email protected]' },
      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);

回答by Jim Factor

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

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

How would I run server-side code in Firebase?

我将如何在 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.

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

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

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