Angular 2如何发送PHP邮件? [英] Angular 2 How to send mail PHP?

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

问题描述

我正在学习angular 2,但我在网络上没有看到任何示例可以将一个简单的联系表从angular 2发送到php scrip.

I learning angular 2, and I don't see any example on the web to send a simple contact form from angular 2 to php scrip.

我的html模板.

<form novalidate="" (ngSubmit)="guardar(forma)" #forma="ngForm">
    <div class="field">
        <label for="name">Nombre:</label>
        <input type="text"
               id="name"
               name="name"
               required
               minlength="3"
               ngModel>
    </div>

    <div class="field">
        <label for="email">Email:</label>
        <input type="email"
               id="email"
               name="email"
               required
               ngModel
               pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">
    </div>

    <div class="field">
        <label for="message">Mensaje:</label>
        <textarea id="message"
                  name="message"
                  required
                  ngModel></textarea>
    </div>

    <div class="field">
        <button [disabled]="!forma.valid"
                type="submit">
            Enviar
        </button>
    </div>
</form>

PHP脚本

<?php
    $name = strip_tags(trim($_POST["name"]));
    $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    $recipient = "nexsmedia@gmail.com";
    $subject = "New contact from $name";

    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    $email_headers = "From: $name <$email>";

    mail($recipient, $subject, $email_content, $email_headers)
?>

我不完整的角度2分量. 我已经在我的应用程序组件HttpModule和FormsModule中导入了

My incomplete angular 2 component. I already have imported in my app component HttpModule and FormsModule

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Http } from '@angular/http';

@Component({
    selector: 'app-contacto',
    templateUrl: './contacto.component.html',
    styleUrls: ['./contacto.component.scss']
})
export class ContactoComponent {
    title = 'Contacto';

    constructor( private http: Http){}

    url='http://myUrl.com/mailerscript.php';

    name:string;
    email:string;
    message:string;

    guardar( forma:NgForm ) {

        this.name = 'name='+forma.value.name;
        this.email = 'email='+forma.value.email;
        this.message = 'message='+forma.value.message;

        /*??*/
        this.http.post(this.url, "");

    }
}

推荐答案

您似乎被困在Angular和PHP之间的接口上-这是可以理解的,因为它不像通过$_POST超全局变量访问变量那么简单.

You seem to be stuck on the interface between Angular and PHP - it's understandable because it's not as trivial as accessing variables via the $_POST superglobal.

默认情况下,Angular将请求主体中传递的数据作为 json 字符串提交,因此您必须访问原始请求主体并将其解析为可用的PHP变量.

By default, Angular submits data passed to it in the request body as a json string, so you have to access the raw request body and parse it into usable PHP variables.

以下示例显示了执行此操作的最基本方法,而无需其他框架或其他依赖项.您可以(并且应该)遵循更好的组织惯例,并将此内容移至服务中,但这又增加了一层不必要的复杂性:

The following example shows the most basic way to do this without extra frameworks or other dependencies. You could (and should) follow better organization practices and move this content to a service, but that's adding an extra layer of complication that isn't needed here:

import { Component, OnInit } from '@angular/core';
import {Http} from "@angular/http";

@Component({
  selector: 'app-mailer',
  template: '<button (click)="sendEmail()">Send the Email</button>'
})
export class MailerComponent implements OnInit {

  email : string;
  name : string;
  message : string;
  endpoint : string;

  http : Http;

  constructor(http : Http) {
    this.http = http;
  }

  ngOnInit() {
    //This data could really come from some inputs on the interface - but let's keep it simple.
    this.email = "hpierce@example.com";
    this.name = "Hayden Pierce";
    this.message = "Hello, this is Hayden.";

    //Start php via the built in server: $ php -S localhost:8000
    this.endpoint = "http://localhost:8000/sendEmail.php";
  }

  sendEmail(){
    let postVars = {
      email : this.email,
      name : this.name,
      message : this.message
    };

    //You may also want to check the response. But again, let's keep it simple.
    this.http.post(this.endpoint, postVars)
        .subscribe(
            response => console.log(response),
            response => console.log(response)
        )
  }
}

还有PHP脚本.请注意,这会检查多种请求方法.它也检查OPTIONS请求. >为什么这是必需的.

And the PHP script. Note that this checks for multiple request methods. It checks for an OPTIONS request too. See why this is nessesary.

为了使操作尽可能简单,我跳过了对来自Angular的输入的清理,这被认为是一个严重的安全问题.您应该将其添加到面向生产的应用程序中:

In order to keep this as simple as possible, I've skipped sanitizing the input from Angular, which is considered a severe security issue. You should add that in for production facing apps:

<?php

switch($_SERVER['REQUEST_METHOD']){
    case("OPTIONS"): //Allow preflighting to take place.
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST");
        header("Access-Control-Allow-Headers: content-type");
        exit;
    case("POST"): //Send the email;
        header("Access-Control-Allow-Origin: *");

        $json = file_get_contents('php://input');

        $params = json_decode($json);

        $email = $params->email;
        $name = $params->name;
        $message = $params->message;

        $recipient = 'targetInbox@exmaple.com';
        $subject = 'new message';
        $headers = "From: $name <$email>";

        mail($recipient, $subject, $message, $headers);
        break;
    default: //Reject any non POST or OPTIONS requests.
        header("Allow: POST", true, 405);
        exit;
}

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

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