Email will not send Angular 4 and PHP

I am trying to send an email from the contact form that is on my page, I use a PHP script to send it to my email address, I follow this tutorial, I used its example, and it works ... but I can not force it to work in my application, I had problems at first with 404 , but then I published my site and posted it on a real server, and now I get success codes.

enter image description here

but I do not receive emails, so I went to http: //mysite/assets/email.php and saw this error

enter image description here

get in-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'); } ?> 

I have never done anything like this before (Angular + PHP), but I did everything that is said in the tutorial and I can not get it to work, any help would be appreciated and please let me know if you need more information

+5
source share
2 answers

At the moment, it seems that the request does not even reach your PHP script, since the request returns 404. Probably the first error occurs because the node server does not execute .php files. You will need to configure the local Apache server on a different port using something like xammp (or your preferred option). Or else make your request on the web server in real time.

It looks like the second and third error messages may appear in your .catch in your email, try using the following:

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

There are several alternatives to using PHP, such as formspree or even the Gmail API , and I'm sure you will find others with a bit of Google. But here is an example using fromspree .

You can also slightly simplify the PHP script as follows:

 <?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
source

I am not 100% sure that I can give you an exact answer, but I think that there are some common problems / confusions / misunderstandings that you encounter, and understanding them can help you move in the right direction.

First of all, you should now ignore angular and only consider PHP (which you tried to do). angular is basically red-herring: if you can get your PHP script to send emails without using Angular, then it will be easy to get angular to send emails using the PHP endpoint. The trick is that your script is currently accepting its input through the POST body using JSON, so if you just load it into your browser, nothing will happen. Instead, you can test this endpoint directly with things like curl. If you have curl installed, you can do something like this from the command line:

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

The d flag indicates message data (and implicit flags for the POST request). If you do not have localization, you can use the online curl or set up a postman. These are tools you could start learning now.

This will allow you to debug your PHP endpoint more efficiently. Most importantly, you can see the exit directly. The next step is to copy and paste the output into something like jsonlint . It looks like your PHP endpoint is not returning JSON properly, and this will allow you to understand this part. Most importantly, you can ignore angular and find out why you are not sending emails. On this note, go to PHP and talk about some common problems in your code that may or may not cause problems, but certainly don't help your case:

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

This first part is pretty obvious to those who are looking at your code for the first time. You make $errors empty, and then all your email sending logic ends up in an if (empty($errors)) state. Lose the $errors variable. Lose this if-else. Never leave code in your application that doesn't actually do anything. It just gives you more options for introducing errors for no reason.

Also, this is a minor point, but you are not doing input validation. If JSON is sent to the endpoint, you are missing data that your script will crash. Someone may put HTML in a message, which can be unpleasant at best or dangerous at worst.

You also have a bunch of errors at the end of your script:

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

You output $response_array as JSON to the browser, then you run json_encode on a line ( $from_email ) that will not even form a valid JSON, and the combination of them will definitely not be valid JSON. You should have only one echo json_encode , otherwise the result will not be valid JSON and you will get a parsing error in your angular interface.

Next, you pass $response_array to the php header function. It definitely does nothing for you. header expects a string, not an array, and is used to set HTTP / HTTP key pairs in an HTTP response. I cannot imagine that you want to set any data in your $response_array values โ€‹โ€‹as HTTP headers, and even if you want it, you cannot do this by passing $response_array . Therefore, be sure to kill this line. PHP ignores it anyway.

Similarly, there is no reason to return anything. Returning from a file executed by an HTTP request will have no effect. As a rule, you should not go back beyond functions (and this is not a function). Although I don't think this line causes any errors, it also does nothing. If he does nothing, delete it. To be clear, I'm talking about this line: return $from_email; .

All of this script should consist of reading in the mail data, sending an email, and then repeating a single json_encode call. Anything else that ends up with invalid JSON that your external application cannot read. Again, use curl (or other similar tools) to directly invoke your PHP script and debug it. That way you can see what it outputs and verify that it returns the correct JSON.

Email

Now, the main problem: the lack of sending email. You definitely have invalid email headers. Each mail header must end with \r\n . You start well, but your last two header lines do not end properly. This may be enough to sink attempts to send e-mail. PHP, which is built into the mail function, does not notify you very well of errors, so you might be better off using a more robust email program. This will give you the best feedback if you are mistaken in setting up your email. Common in PHP is this guy:

https://github.com/PHPMailer/PHPMailer

I would start by fixing the email headers and see if that helps you. Otherwise, you may have to try out the actual email program. The reason is that the next most common reason email doesn't work is due to modern spam mitigation efforts. The PHP mail function will send email directly from the server itself. Many modern email systems (especially gmail) will automatically reject such messages, unless the domain name you are sending is correctly configured at the DNS level. However, you send from arbitrary email addresses (the contents of the variable $from_email , which comes from the user). Many email providers these days will automatically refuse such emails, and PHP will not know what happened and will not give you any instructions.

Instead, send from a fixed address that you control. Either follow $from_email in the email, or set it as the answer. It is best to use the actual email address and authenticate using SMTP. Gmail actually works great for this. You should find some examples of using the above PHPMailer with gmail to send directly from your gmail address. This minimizes the likelihood of rejection of your emails as spam, and also gives you additional feedback (if it is in your sent field, but does not appear, then it was rejected as spam).

Sending email today is complicated. This is not as simple as calling the mail function.

+3
source

Source: https://habr.com/ru/post/1274084/


All Articles