VisDesign
VisDesign

Reputation: 392

Can send email using URL on Browser but on Angular it does not work

If I call the script on browser it does send email to my domain email. Anyway I'm trying to send some contact email from angular 7 apps. I did use HttpClient post and try to send the data as JSON. (Apache server PHP -v 5.6)

I have tried to send the data with URL like mail.php?param1="[email protected]"&param2="Test email". I did not have any luck. I tried file_get_contents("php://input"); no luck either.

<?php
echo("called");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');

  // Sanitize.
 // $title = $_GET['title'];;
 // $message = $_GET['message'];;
 // $name    = $_GET['name'];;
 // $from = $_GET['from'];;

  $title = $request->title;
  $message = $request->message;
  $name    = $request->name;
  $from = $request->from;
  $to = "[email protected]";


  // Sending email
  if(mail($to, $title, $message, $name)){
      echo 'Your mail has been sent successfully.';
  } else{
      echo 'Unable to send email. Please try again.';
  }


?>

Here is my Angular Service

export class PollServiceService {

  PHP_API_SERVER: string = "/api";
  constructor(private http: HttpClient) {
   }


  public SendEmail(e: any): Observable<any>{
    var tmp1 = "/?title=" + e.title + "&message=" +e.message + "&name=" +e.name + "&from=" + e.from ;
    return this.http.post<any>(`${this.PHP_API_SERVER}/mail.php`, e);
  }
}

I do call the SendEmail(e: any) method on the form. Anyway it does not seem to do to anything. I'm suspect that the php file does not get called at all from the script. Thanks in advance guys.

Upvotes: 0

Views: 314

Answers (1)

Simon Echle
Simon Echle

Reputation: 296

Your SendEmail function returns an Observable.

You have to subsribe to this Observable in order to make the call happen.

So you should do something like that in a function in your component:

this.pollServiceService.SendEmail(e).subscribe(res => {
    // here you can do whatever you want with the result of the call
});

this function should then be called from your form.

Upvotes: 2

Related Questions