Reputation: 169
I am sending an email from a form using PHPMailer and Angular, but I get an error log every time I send the data: PHP Notice: Undefined variable: name, email and message. Therefore, I get the mail in my email account, but it has no data from the form. My html inputs already have the attribute name.
My code is:
<?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 = '[email protected]';
$mail->Password = '*****';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 587;
//Recipients
$mail->setFrom('[email protected]', 'Ptree');
$mail->addAddress('[email protected]');
//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;
}
?>
This is my Angular service, Does it lack something?
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', []))
);
}
}
Also I added my form.component.ts file
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);
}
);
}
}
Upvotes: 1
Views: 1954
Reputation: 37790
Delete this line as this file no longer exists in PHPMailer:
require 'PHPMailer/PHPMailerAutoload.php';
This line:
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
will output debug information, which will corrupt the integrity of any JSON you're meant to be returning to the browser, and is likely the cause of your JSON parsing failure. Disable debug output by either deleting that line, or setting it to false.
$mail->SMTPDebug = false;
In general, to debug this kind of issue, you should be using your browser's inspector console to look at exactly what is coming back from your XHR requests – this debug output would be very obvious in there.
You're also asking PHPMailer to throw exceptions (by passing true
to the constructor), but you are not using a try/catch block, so if the send fails, you will get a fatal unhandled exception and will never see your error output.
Upvotes: 1