首页 > 解决方案 > PHPMailer 注意:未定义的变量

问题描述

我正在使用 PHPMailer 和 Angular 从表单发送电子邮件,但每次发送数据时都会收到错误日志:PHP 通知:未定义变量:名称、电子邮件和消息。因此,我在我的电子邮件帐户中收到了邮件,但它没有来自表单的数据。我的 html 输入已经具有属性名称。

我的代码是:

<?php

require 'PHPMailer/PHPMailerAutoload.php';

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

use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

if(isset($_POST['nombre']) && isset($_POST['email']) && isset($_POST['mensaje'])){
    
    $nombre = $_POST['nombre'];
    $email = $_POST['email'];
    $mensaje = $_POST['mensaje']; 
}

$mail = new PHPMailer(true);

    //Server settings

    $mail->SMTPDebug = SMTP::DEBUG_SERVER; 
    $mail->Host       = 'smtp.gmail.com';                     
    $mail->SMTPAuth   = true;                                  
    $mail->Username   = 'kanazawa8213@gmail.com';
    $mail->Password   = '*****';                             
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;           
    $mail->Port       = 587;  

    //Recipients
    $mail->setFrom('kanazawa8213@gmail.com', 'Ptree');
    $mail->addAddress('kanazawa8213@gmail.com');     

    //Content
    $mail->isHTML(true);                                 
    $mail->Subject = 'Nuevo mensaje desde Ptree site';

    $mail->Body = "Este es un mensaje desde Ptree site:\n\n".
        " Nombre: ".$nombre.
        "\n\n Email: ".$email.
        "\n\n Mensaje: " .$mensaje;


if($mail->send()){
        echo 'Message has been sent';
    }else{
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    }


?>

这是我的 Angular 服务,它缺少什么吗?


import { Injectable } from '@angular/core';
import { Observable, of, from } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
import { environment } from '../../environments/environment';

const httpOptions = {
    headers: new HttpHeaders({'Content-Type':'application/json'})
};

@Injectable({
  providedIn: 'root'
})
export class MycontactService {

  apiUrl = environment.apiUrl;
  emailUrl = environment.emailUrl;

  constructor(private http:HttpClient) { }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      console.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    }
  }


  sendMessage(landingForm:any): Observable<any> {
    return this.http.post<any>(`${this.emailUrl}`, landingForm, httpOptions).pipe(
        tap(
            message => console.log(message)
        ),
        catchError(this.handleError('Sending', []))
    );
  }

}

我还添加了我的 form.component.ts 文件


 import { Component, OnInit, AfterViewInit, ElementRef, Inject, PLATFORM_ID } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl, NgForm  } from '@angular/forms';
import { isPlatformBrowser } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { MycontactService } from '../../services/mycontact.service';
import { AngularFirestore } from '@angular/fire/firestore';
import { Router } from '@angular/router';

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


  landingForm!: FormGroup;
  public href: string = "";

  loading = false;
  buttonText = "Enviar";  

  showMsg: boolean = false;

  sending!: boolean;


  constructor(private el: ElementRef,
              private fb: FormBuilder,
          private http: HttpClient,
          private contactService: MycontactService,
              // public db: AngularFirestore,
              private router: Router,
              @Inject(PLATFORM_ID) private platformId: Object
            ) { }

  ngOnInit(): void {

        this.href = this.router.url;
        console.log('Hola ' + this.href);

        this.landingForm = this.fb.group({
          opciones: ['', Validators.required],
          nombre: ['', [Validators.required, Validators.pattern(/^([a-zA-Z ]|[à-ú]|[À-Ú])+$/)]],
          // email: ['', [Validators.required, Validators.pattern(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/)]],
          email: ['', [Validators.required, Validators.pattern(/^([\w-.]+@(?!gmail\.com)(?!yahoo\.com)(?!hotmail\.com)([\w-]+.)+[\w-]{2,})?$/)]],
          telefono: [null, Validators.compose([Validators.required, Validators.minLength(8), Validators.maxLength(13), Validators.pattern(/^[0-9 ]*$/)])],
          empresa: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(50)]],
          mensaje: ['', [Validators.minLength(1), Validators.maxLength(250)]],
          empleados: ['', Validators.required],
          pais: ['', Validators.required],
          acceptTerms: ['', Validators.required],
        recaptcha: ['', Validators.required],
          timestamp: [''],
          // campana: ['home'],
          // version: ['1'],
          referrer: [this.router.url]
        });

      console.log(this.router.url);
      this.sending = false;
  }

  siteKey:string = "6LeSbRAcAAAAAGXmlbPS9AIyclXwT1YTT_mJ1i50";
 
  ngAfterViewInit() {   
  }



    onSubmit(landingForm:any){
      this.sending = true;
      console.log(landingForm);
      this.contactService.sendMessage(landingForm).subscribe(
        data => {
          console.log(data);
          this.showMsg = true;
          setTimeout( () => {                           // 
            this.showMsg = false;
          }, 3000);
        } 
      );


      
     
    }




}


标签: javascriptphpangularphpmailer

解决方案


删除此行,因为 PHPMailer 中不再存在此文件:

require 'PHPMailer/PHPMailerAutoload.php';

这一行:

$mail->SMTPDebug = SMTP::DEBUG_SERVER;

将输出调试信息,这将破坏您要返回到浏览器的任何 JSON 的完整性,并且可能是您的 JSON 解析失败的原因。通过删除该行或将其设置为 false 来禁用调试输出。

$mail->SMTPDebug = false;

一般来说,要调试此类问题,您应该使用浏览器的检查器控制台来查看 XHR 请求返回的确切内容——该调试输出在那里非常明显。

您还要求 PHPMailer 抛出异常(通过传递true给构造函数),但您没有使用 try/catch 块,因此如果发送失败,您将收到一个致命的未处理异常,并且永远不会看到您的错误输出。


推荐阅读