How can PHPMailer be utilized to send emails with dynamically generated image attachments in PHP?
To send emails with dynamically generated image attachments using PHPMailer, you can generate the image using PHP, save it to a temporary file, and then attach it to the email before sending it using PHPMailer.
// Generate image dynamically
$image = imagecreate(200, 200);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 4, 50, 50, 'Dynamic Image', $textColor);
// Save image to a temporary file
$imagePath = tempnam(sys_get_temp_dir(), 'image') . '.png';
imagepng($image, $imagePath);
// Send email with dynamically generated image attachment
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->setFrom('your@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Dynamic Image Attachment';
$mail->Body = 'Please see the attached image.';
$mail->addAttachment($imagePath, 'dynamic_image.png');
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
// Clean up temporary image file
unlink($imagePath);