PHPMailer通知:未定义变量



我正在使用PHPMailer和Angular从表单发送电子邮件,但是每次我发送数据时都会得到一个错误日志:PHP注意:未定义变量:名称,电子邮件和消息。因此,我把邮件在我的邮箱,但是没有来自表单的数据。我的html输入已经有了属性名。

我的代码是:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
require 'includes/PHPMailer.php';
require 'includes/SMTP.php';
require 'includes/Exception.php';
use PHPMailerPHPMailerException;
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
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:nn".
" Nombre: ".$nombre.
"nn Email: ".$email.
"nn 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);
} 
);



}


}

删除这一行,因为这个文件在PHPMailer中不再存在:

require 'PHPMailer/PHPMailerAutoload.php';

这条线:

$mail->SMTPDebug = SMTP::DEBUG_SERVER;

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

$mail->SMTPDebug = false;

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

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

最新更新