php | Email sender with QR code

Send email with inline QR code

First make sure to include PHPMailer in the project

// ========================= Email Sender ==========================

// Button click to send
if (array_key_exists('btn_send_email', $_POST)) {
    send_email();
}

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

function send_email() {
    require PATH_system . "/controller/PHPMailer/src/PHPMailer.php";
    require PATH_system . "/controller/PHPMailer/src/Exception.php";
    require PATH_system . "/controller/PHPMailer/src/SMTP.php";

// Replace these variables with your Google Workspace email and app-specific password
$senderEmail = "sender@myemail.com";
$appPassword = "get password from google apps password";
$recipientEmail = "recipient@email";

$subject = "Your QR Code";
$message = "Please find your QR code below.";
$id = $GLOBALS["val"][0]; // Replace with your dynamic ID

// Construct the URL for the Google Chart API with your dynamic data
$qrCodeData = "https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=" . urlencode("https://myWebSiteURL/qr/scan.php?id=" . $id);

// Create a PHPMailer instance
$mail = new PHPMailer;
//$mail = new PHPMailer(TRUE);

// Enable debugging (remove this line in production)
$mail->SMTPDebug = 2;

// Set the mailer to use SMTP
$mail->isSMTP();

// Specify the SMTP server
$mail->Host = 'smtp.gmail.com';

// Enable SMTP authentication
$mail->SMTPAuth = true;

// SMTP username (your Google Workspace email)
$mail->Username = $senderEmail;

// SMTP password (your app-specific password)
$mail->Password = $appPassword;

// Enable TLS encryption
$mail->SMTPSecure = 'tls';

// Set the SMTP port (587 for TLS, 465 for SSL)
$mail->Port = 587;

// Set the 'From' email address
$mail->setFrom($senderEmail);

// Set the 'To' email address
$mail->addAddress($recipientEmail);

// Set the email subject
$mail->Subject = $subject;

// HTML version of the email with the inline image
$mail->isHTML(true);
$mail->Body = "<p>$message</p><img src='$qrCodeData' alt='QR Code' /><br />";

// Send the email
if ($mail->send()) {
    //echo "Email sent successfully.";
    eventlog(1, $person_id, "Email Invitation Sent", $_SESSION["user_id"]);
} else {
    eventlog(1, $person_id, "Email Invitation Sending <b>Faild</b>", $_SESSION["user_id"]);
}

}

Leave a Reply

Your email address will not be published. Required fields are marked *