电子邮件不会发送Angular 4和PHP

问题描述 投票:5回答:2

我正在尝试从我页面上的联系表单发送电子邮件,我正在使用PHP脚本将其发送到我的电子邮件,我正在关注this教程,我已经使用了他的示例,它确实有效。 ..但我似乎无法让它在我的应用程序中工作,我最初遇到一些问题404错误但我然后发布我的网站并把它放在一个实时服务器上,现在我得到成功代码

enter image description here

但我没有收到电子邮件,所以我去了http://mysite/assets/email.php,我看到了这个错误

enter image description here

获得功能于touch.component.ts

import { Component, OnInit } from '@angular/core';
import { AppService, IMessage } from '../../services/email.service';

@Component({
  selector: 'app-get-in-touch',
  templateUrl: './get-in-touch.component.html',
  styleUrls: ['./get-in-touch.component.scss'],
  providers: [AppService]
})
export class GetInTouchComponent implements OnInit {
  message: IMessage = {};

  constructor(
    private appService: AppService
  ) { }

  ngOnInit() {
  }

  sendEmail(message: IMessage) {
    this.appService.sendEmail(message).subscribe(res => {
      console.log('AppComponent Success', res);
    }, error => {
      console.log('AppComponent Error', error);
    });
  }

}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes, ActivatedRoute, ParamMap } from '@angular/router';


import { AppComponent } from './app.component';
import { GetInTouchComponent } from './get-in-touch/get-in-touch.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { httpModule } from @angular/forms;

export const ROUTES: Routes = [
  { path: 'get-in-touch', component: GetInTouchComponent }
];

 @NgModule({
   declarations: [
    AppComponent,
    GetInTouchComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(ROUTES),
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

email.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Resolve } from '@angular/router';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

export interface IMessage {
  name?: string;
  email?: string;
  message?: string;
}

@Injectable()
export class AppService {
  private emailUrl = '../app/get-in-touch/email.php';

  constructor(private http: Http) {

  }

  sendEmail(message: IMessage): Observable<IMessage> | any {
    return this.http.post(this.emailUrl, message)
      .map(response => {
        console.log('Sending email was successfull', response);
        return response;
      })
      .catch(error => {
        console.log('Sending email got error', error);
        return Observable.throw(error);
      });
  }
}

email.php

<?php

header('Content-type: application/json');

$errors = '';

if(empty($errors)){
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);

    $from_email = $request->email;
    $message = $request->message;
    $from_name = $request->name;

    $to_email = $from_email;

    $contact = "<p><strong>Name: </strong> $from_name</p><p><strong>Email:</strong> $from_email</p>";
    $content = "<p>$message</p>";

    $website = "Thirsty Studios";
    $email_subject = "Contact Form";

    $email_body = '<html><body>';
    $email_body .= '$contact $content';
    $email_body .= '</body></html>';

    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $headers .= "From: $from_email\n";
    $headers .= "Reply-To: $from_email";

    mail($to_email,$email_subject,$email_body,$headers);

    $response_array['status'] = 'success';
    $response_array['from'] = $from_email;
    echo json_encode($response_array);
    echo json_encode($from_email);
    header($response_array);
    return $from_email;
} else {
    $response_array['status'] = 'error';
    echo json_encode($response_array);
    header('Location: /error.html');
}
?>

我以前从未做过这样的事(Angular + PHP),但是我已经完成了教程中所说的一切,我似乎无法让它工作,任何帮助都会受到赞赏,请告诉我,如果你需要更多信息

javascript php angular email typescript
2个回答
3
投票

此时似乎请求甚至没有到达您的PHP脚本,因为请求返回404.第一个错误可能发生,因为节点服务器将不执行.php文件。您需要使用xammp(或您首选的替代方案)之类的东西在不同的端口上设置本地Apache服务器。或以其他方式向实时Web服务器发出请求。

看起来第二条和第三条错误消息可能来自您的电子邮件服务中的.catch回调,请尝试使用以下内容:

.catch((error: Error) => {
  console.log('Sending email got error', error.message);
  return Observable.throw(error.message);
});

有一些使用PHP的替代方法,例如formspree甚至Gmail API,我相信你会发现其他人有一些谷歌搜索。但这是一个example using fromspree

您还应该能够简化PHP脚本,如下所示:

<?php
$errors = '';

if( empty( $errors ) ) {

    $response_array = array();

    $from_email = $_POST['email'];
    $message    = $_POST['message'];
    $from_name  = $_POST['name'];

    $to_email = $from_email;

    $contact = "<p><strong>Name: </strong> $from_name</p><p><strong>Email:</strong> $from_email</p>";
    $content = "<p>$message</p>";

    $website = "Thirsty Studios";
    $email_subject = "Contact Form";

    $email_body = "<html><body>";
    $email_body .= "$contact $content";
    $email_body .= "</body></html>";

    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $headers .= "From: $from_email\n";
    $headers .= "Reply-To: $from_email";

    mail( $to_email, $email_subject, $email_body, $headers );

    $response_array['status'] = 'success';
    $response_array['from'] = $from_email;
    echo json_encode( $response_array );

} else {

    $response_array['status'] = 'error';
    echo json_encode($response_array);
}
?>

3
投票

我并不是100%相信我可以给你一个确切的答案,但我认为你遇到了一些整体问题/困惑/误解,理解它们可能会帮助你朝着正确的方向前进。

首先,您应该暂时忽略角度,并且只考虑PHP(您尝试过这样做)。 Angular基本上是一个红鲱鱼:如果你可以让你的PHP脚本在不使用Angular的情况下发送电子邮件,那么很容易让Angular使用PHP端点发送电子邮件。诀窍是你的脚本目前通过带有JSON的POST主体接受它的输入,所以如果你只是在浏览器中加载它,那么什么都不会发生。相反,您可以直接使用curl等测试此端点。如果你安装了curl,你可以从命令行执行以下操作:

curl -d '{"email":"[email protected]", "message": "Hi", "name": "Conor Mancone"}' 'http://example.com/email.php'

d标志指定发布数据(以及POST请求的隐式标志)。如果您没有在本地安装curl,可以使用online curl或安装邮递员。这些是您现在可以开始学习的工具。

这将使您更有效地调试PHP端点。最重要的是,您将能够直接看到输出。下一步是将输出复制并粘贴到jsonlint之类的内容中。看起来你的PHP端点没有正确返回JSON,这会让你想出那个部分。最重要的是,您可以忽略角度并找出您不发送电子邮件的原因。在这方面,让我们跳进PHP并讨论代码中的一些常见问题,这些问题可能会或可能不会导致您的问题,但肯定无法帮助您解决问题:

$errors = '';

if(empty($errors)){
    // send email
} else {
    // return error
}

第一部分对于第一次查看代码的人来说相当明显。你使$errors为空,然后你的所有电子邮件发送逻辑都包含在if (empty($errors))条件下。丢失$errors变量。失去了if-else。永远不要在应用程序中留下实际上没有做任何事情的代码。它只是给你更多机会无缘无故地引入bug。

此外,这是一个小问题,但您没有进行任何输入验证。如果发布到您的端点的JSON缺少某些数据,则脚本将崩溃。有人可能会将HTML放在最好是令人讨厌或最坏的情况下。

您的脚本末尾还有一堆错误:

echo json_encode($response_array);
echo json_encode($from_email);
header($response_array);
return $from_email;

您正在将$response_array作为JSON输出到浏览器,然后您在字符串(json_encode)上运行$from_email,它甚至不会形成有效的JSON,并且它们的组合肯定不会是有效的JSON。你应该只有一个echo json_encode,否则结果将不是有效的JSON,并且你的角度前端会得到一个解析错误。

接下来,你将你的$response_array传递给php header函数。这绝对不会为你做任何事情。 header期望一个字符串,而不是一个数组,并用于在HTTP响应中设置HTTP头键/值对。我无法想象您想要将$response_array中的任何数据设置为HTTP标头响应值,即使您确实想要这样做,也不能通过传入$response_array本身来实现。因此,绝对杀死这条线。无论如何,PHP无声地忽略它。

同样,没有理由退货。从HTTP请求执行的文件返回将完全没有影响。通常,您不应该在函数之外返回(这不是函数)。虽然我不相信这条线导致任何错误,但它也没有做任何事情。如果它没有做任何事情,那么删除它。要清楚,我在谈论这一行:return $from_email;

这个脚本应该做的就是读取帖子数据,发送电子邮件,然后回复一次对json_encode的调用。除此之外的任何内容都将导致您的前端应用程序无法读取的无效JSON。再次,使用curl(或其他类似工具)直接调用PHP脚本并更容易地调试它。通过这种方式,您可以查看输出内容并验证它是否返回了正确的JSON。

电子邮件

现在,关于主要问题:缺少电子邮件发送。你肯定有一些格式错误的邮件标题。每个邮件标题都需要以\r\n结尾。你开始不错,但你的最后两个标题行没有正确结束。这可能足以让您的电子邮件发送尝试。 PHP的内置mail功能并不能很好地通知你错误,所以你可能最好使用更强大的邮件程序。如果您在配置电子邮件时出错,这将为您提供更好的反馈。 PHP中常见的一个就是这个人:

https://github.com/PHPMailer/PHPMailer

我首先修复您的电子邮件标题,看看是否适合您。否则,您可能需要尝试实际的邮件。原因是因为电子邮件发送不起作用的下一个最常见原因是因为垃圾邮件缓解的现代努力。 PHP mail函数将直接从服务器本身发送电子邮件。许多现代电子邮件系统(尤其是gmail)会自动拒绝此类电子邮件,除非您发送的域名在DNS级别正确配置。但是,您从任意电子邮件地址发送($from_email变量的内容来自用户)。如今,许多电子邮件提供商都会自动拒绝此类电子邮件,而PHP将不知道发生了什么,也不会给您任何指示。

而是从您控制的固定地址发送。要么在电子邮件中传递$from_email,要么将其设置为回复。您最好的选择是使用实际的电子邮件地址并使用SMTP进行身份验证。 Gmail实际上可以正常使用。您应该能够找到一些如何使用上面的PHPMailer与gmail直接从您的Gmail地址发送的示例。这样可以最大限度地减少您的电子邮件被拒绝为垃圾邮件的可能性,还会向您提供其他反馈(如果它在您发送的邮箱中,但没有显示,则会被拒绝为垃圾邮件)。

这些天发送电子邮件很棘手。它并不像调用mail函数那么简单。

© www.soinside.com 2019 - 2024. All rights reserved.