user16648336
user16648336

Reputation:

PHPMailer send base64 image from database

I'm trying to attach base64 images in my PHPMailer email.

Is it possible to do this? How can I attach $base64Images array of images to email? On email I get files with not supported format.

$base64Images = array(3){
    [0]=>
    string(2747277) "data:image/jpeg;base64,9j/4AAA ..."
    [1]=>
    string(2747277) "data:image/jpeg;base64,9j/4AAA ..."
    [2]=>
    string(2747277) "data:image/jpeg;base64,9j/4AAA ..."
}

My email function.

try {
  $mail = new PHPMailer(true);
  if ($smtp) {
    $mail->IsSMTP();
    $mail->SMTPKeepAlive = true;
    $mail->Host = $smtp;
    $mail->Port = $port;
    if ($auth) {
      $mail->SMTPAuth = true;
      $mail->Username = $auth_user;
      $mail->Password = $auth_password;
    }
  }
  $mail->CharSet = 'utf-8';
  $mail->ContentType = 'text/html';
  $mail->SetFrom($sender);
  $mail->AddAddress($recipient);
  $mail->Subject = $mailSubject;
  $mail->MsgHTML($mailBody);

Attach to email.

  foreach ($base64Images as $base64Image) {
    $mail->AddStringAttachment($base64Image, 'Filename.jpeg', 'base64', 'image/jpeg');
  }


  if(!$mail->Send())
  {
    Log::write( "Error sending : " . $mail->ErrorInfo . " mailSubject :" . $mailSubject );
  }else {
    Log::write( "Email was successfully sent);
  }
} catch (Exception $e) {
  Log::write("{$e->getCode()}: {$e->getMessage()} in {$e->getFile()} at line {$e->getLine()}");

}

Upvotes: 0

Views: 1110

Answers (1)

Rateb Habbab
Rateb Habbab

Reputation: 1789

Pass your base64 encoded images as an HTML Tags, then set the mail config IsHTML to true, Like:

$Body = '<img src="' . $base64Images[0] . '"/>'
$mail->Body = $Body;
$mail->IsHTML(true);

If you want to attach images to email, you should just call base64_decode it without changing anything, and then pass it in. It should work. (Of course, decode it without the data:image/png;base64, heading texts).

Upvotes: 3

Related Questions