从Angular发送电子邮件2 [英] Sending Email from Angular 2

查看:443
本文介绍了从Angular发送电子邮件2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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


$ b

客户端进度



<这是我的表单:



<! - contact-form

 






这是我的联系表单组件:

// contact-从'@ angular / core'中导入{component};从'./contact-form.service'中导入{ContactFormService}; @ Component({selector:'contact-form',templateUrl:'./contact- (); form.content.content.contact.css'],提供者:[ContactFormService]})导出类ContactFormComponent {构造函数(私人formService:ContactFormService){formService.buildForm(); }}



这是我的联系表单服务:



<@ c $ c> // contact-form.service.tsimport {Injectable} from @ angular / core ';导入{FormGroup,FormBuilder,FormControl,Validators}从@角度/形式; @ Injectable()导出类ContactFormService {构造函数(公共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();当我点击提交按钮,表单数据将会


$ b

服务器端Nodejs进度



<我可以使用SendGrid和Nodejs成功发送命令提示符下的邮件: >

  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 '}],主题:'来自Node.js的Sendgrid测试邮件'}],来自:{email:'noreply@email-app.firebaseapp.com'},内容:[{type:'text / plain',value: 'H你好Joe!你能听到我吗?}}}}); Sendgrid.API(request,function(error,response){if(error){console.log('Mail not sent;看到下面的错误信息。'); } else {console.log('Mail sent successfully!'); } console.log(response);});  

然后如果我在命令提示符下输入这个邮件,邮件将成功发送:

  node sendmail 






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



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

解决方案

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

$ pre $ const $ Sendgrid = require -api-key-placed-here>'
);

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
$ b // //解析应用程序/ x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
$ b app.post('/ send-mail',function(req,res){
//把你的发送邮件逻辑放在这里,req.body应该有你提交的表单的值
sendMail(req.body);
res.header(Access-Control-Allow-Origin,*);
res.header(Access-Control-Allow-Headers, ;
res.send('SEND MAIL');
})

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


函数sendMail(formData){
let request = Sendgrid.emptyRequest({ b $ b方法:'POST',
路径:'/ v3 / mail / send',
主体:{
个性化:[{
to:[{email:' myemail@gmail.com'}],
主题:'从Node.js'
}],
的Sendgrid测试电子邮件地址:{email:'noreply@email-app.firebaseapp .com'},
content:[{
type:'text / plain',
value:`Hello $ {formData.userFirstName} $ {formData.userLastName}!Ca ñ你听到我$ {formData.userFirstName}?。`
}]
}
});

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

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

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

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


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!

解决方案

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

这篇关于从Angular发送电子邮件2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆