Skip to main content

PHP en GMAIL

In (any) project directory:

composer require phpmailer/phpmailer

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

require 'vendor/autoload.php';

// Your Gmail credentials
$gmailUsername = 'user-name@gmail.com';
$gmailPassword = '16-char-app-password'; // under 2 FA in google account settings

// Recipient email address
$recipientEmail = 'to-user@server.com';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $emailContent = "Form Submission:\n\n";

    foreach ($_POST as $key => $value) {
        $emailContent .= "$key: $value\n";
    }

    $mail = new PHPMailer(true);
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = $gmailUsername;
        $mail->Password = $gmailPassword;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;

        // Recipients
        $mail->setFrom($gmailUsername, 'Form Submission');
        $mail->addAddress($recipientEmail);

        // Content
        $mail->isHTML(false);
        $mail->Subject = 'New Form Submission';
        $mail->Body    = $emailContent;

        $mail->send();
        echo 'Message has been sent';
    } catch (Exception $e) {
        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}
?>