Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mail an image created using php

Tags:

php

email

php-gd

I have the following code that adds the first name and last name onto a predefined image.

function create_image($fname, $lname)
{
 $image = imagecreatefromjpeg('sample.jpg');
 $color = imagecolorallocate($image, 255, 255, 255);
 $font_path = '../fonts/GSMT.TTF';
 $font_size = 18;
 $first_name = $name;
 $last_name = $lname;
 $name = $fname." ". $lname;

// Print Text On Image
imagettftext($image, $font_size, 0, 100, 160, $color, $font_path, $name);

header('Content-type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
}

I use the following email script;

function mailer($email_adrress, $registration_id)
{
$mail = new PHPMailer;

$mail->isSMTP(); // set mailer to use SMTP
$mail->Host = 'mail.server.com'; // set mail server
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->Port = 587; // TCP port to connect to
$mail->IsHTML(true);      
$mail->From = '[email protected]';
$mail->FromName = 'John Doe'; // from name     
$mail->addAddress($email_adrress); // recipient                            

$mail->Subject = 'emailer';
$mail->Body    = "Congratulations you have been Successfully registered.   

if(!$mail->send()) 
{
    die("error mail not sent);
} 
}

When the create_image function is called the image gets created successfully. But my question is instead of printing the image onto the browser how do i mail it. Should i temporarily save the image till the mail is sent and then delete it, or is there another approach?

like image 737
nad Avatar asked Apr 01 '26 12:04

nad


1 Answers

I think you should use output buffering and encode the image to base64 and use it in src tag

ob_start();
// output jpeg (or any other chosen) format & quality
imagejpeg($image);
$contents = ob_get_contents();
ob_end_clean();

Now you need base64 content

$base64 = base64_encode($contents);

now you can use it in your message HTML contents

<img src="data:image/jpeg;base64,$base64">
like image 62
Robert Avatar answered Apr 03 '26 17:04

Robert