Skip to main content

PHP en GMAIL

In (any) project directory:

composer require phpmailer/phpmailer

Create app password in Google

google account - security 0 2-Step Verification - App passwords

emailer

PHP code (this will accept a posted form and email all form fields).

<?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}";
    }
}
?>

Form example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Submission</title>
</head>
<body>
    <form action="process_form.php" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br><br>
        
        <label for="email">Email:</label>
        <input type="email" id="email" name="email"><br><br>
        
        <label for="message">Message:</label>
        <textarea id="message" name="message"></textarea><br><br>
        
        <input type="submit" value="Submit">
    </form>
</body>
</html>