简体   繁体   中英

PHP mailer + angular4 - 404 can't find the issue

i'm trying to do a PHPform to send e-mail using Angular services, the data is being retrieved but server returns 404, since i'm new to PHP, I can't find what I'm missing. Can anybody help me?

I've been searching for angular4 + phpmailer and followed some tutorials, actually I don't think it's the phpcode itself.

Services:

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

    export interface IMessage {
      nome?: string,
      email?: string,
      assunto?:string, 
      mensagem?: string
    }

    @Injectable()
    export class AppService {
      private emailUrl = '../../../api/sendemail.php';

      constructor(private http: Http) {

      }

      sendEmail(message: IMessage): Observable<IMessage> | any {
        return this.http.post(this.emailUrl, message)
          .map(response => {
            console.log('Email enviado com sucesso', response);
            return response;
          })
          .catch(error => {
            console.log('Houve uma falha na solicitação de serviço', error);
            return Observable.throw(error)
          })
      }
    }

Contact.component.ts

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

    @Component({
      selector: 'app-contact',
      templateUrl: './contact.component.html',
      styleUrls: ['./contact.component.scss'],
      providers: [AppService]
    })
    export class ContactComponent implements OnInit {

      message: IMessage = {};

      constructor(private appService: AppService) { }


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

      ngOnInit() {

        function Toggle(){
          var faq = document.querySelectorAll('.faq-box');
          for(var i = 0 ; i < faq.length ; i++ ){
            faq[i].addEventListener('click',function(){
              this.classList.toggle('active');
            })
          }
        }

        Toggle();
      }

    }

PHP

            <?php
            use PHPMailer\PHPMailer\PHPMailer;
            use PHPMailer\PHPMailer\Exception;

            require 'includes/phpmailer/src/Exception.php';
            require 'includes/phpmailer/src/PHPMailer.php';
            require 'includes/phpmailer/src/SMTP.php';


            if( !isset( $_POST['nome'] ) || !isset( $_POST['email'] ) || !isset( $_POST['mensagem'] ) || !isset( $_POST['assunto'] ) ) {

            }

            $pnome = $_POST['nome'];
            $pemail = $_POST['email'];
            $passunto = $_POST['assunto'];
            $pmsg = $_POST['mensagem'];

            $to = "contato@corpomaisleve.com.br";
            $bcc = "";
            $subject = 'Formulário de Contato Corpo Leve - ' . $pnome;
            $body = $pmsg;

            $body = "
            Nome: $pnome
            <br>assunto: $passunto
            <br>
            <br>Mensagem:
            <p>
                $pmsg
            </p>
            ";

            //PHPMailer Object
            $mail = new PHPMailer;

            //From email address and name
            $mail->From = $pemail;
            $mail->FromName = $pnome;

            //To address and name
            $mail->addAddress($to);
            //$mail->addAddress("recepient1@example.com"); //Recipient name is optional

            //Address to which recipient will reply
            $mail->addReplyTo($pemail);

            //CC and BCC
            // $mail->addCC("cc@example.com");
            $mail->addBCC($bcc);

            //Send HTML or Plain Text email
            $mail->isHTML(true);

            $mail->Subject = $subject;
            $mail->Body = $body;
            $mail->AltBody = $body;

            $retorno;

            if(!$mail->send()) 
            {
                $retorno = "Problema";
                echo ":" . $mail->ErrorInfo;
            } 
            else 
            {
                $retorno = "E-mail enviado com sucesso. Você será redirecionado em 3 segundos";
                header( "refresh:3;url=index.php" );
            }
            /*
            $to = "edgar@bulbcriacoes.com.br";
            $subject = 'Formulário de Contato B&F Assessoria - ' . $pnome;
            $body = $pmsg;

            $body = `
            Nome: $pnome
            <br>assunto: $passunto
            <br>
            <br>Mensagem:
            <p>
                $pmsg
            </p>
            `;
            $headers = 'From: ' . $pnome ."\r\n";
            $headers .= 'Reply-To: ' . $pemail ."\r\n";
            $headers .= 'Return-Path: ' . $pemail ."\r\n";
            $headers .= 'X-Mailer: PHP5'."\n";
            $headers .= 'MIME-Version: 1.0'."\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";

            $retorno;

            try {
                if( mail($to, $subject, $body, $headers) ) {
                    header( "refresh:5;url=wherever.php" );
                    $retorno =  "E-mail Enviado com sucesso. Em 3 segundos você será redirecionado, obrigado por entrar em contato!";  
                }

            } catch( Exception $e ) {
                print_r( "Problema:" . e );
            }*/
            ?>
            <!DOCTYPE html>
            <html lang="en">
                <head>
                <meta charset="UTF-8">
                <title>Corpo Leve - E-mail enviado</title>
                <body>
                    <?php
                    echo $retorno;
                    ?>
                </body>
            </html>

You have to run a web server to run PHP script. WAMP XAMP or any web server.

private emailUrl = '../../../api/sendemail.php';

Here the problem is with URL. The emailURL is finding the PHP script in the angular location, so it is giving you the 404.

You need to deploy the PHP file in the web server and then you can access it by the URL.

Example: http://localhost/phpmailer/api/sendemail.php

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM