c.k
c.k

Reputation: 1105

Sending mail with base64 image atttachment using PHPmailer

What is the proper setup to send an email with the image attached to it?.

I created a function for my include.php to get all the details to send using phpmailer:

function send_mail($args){  
require_once('phpmailer/class.phpmailer.php');
$mail = new PHPMailer(true); 
$mail->IsSMTP(); 
$mail->SMTPDebug = 0;
$mail->SMTPAuth   = true;
$mail->Port       = 25;
$mail->Host = "localhost";

$mail->Username = 'myusername';
$mail->Password = "*************";

$mail->From = "[email protected]";
$mail->FromName = "Notification"; 

$mail->Subject = $args['subject'];
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
$mail->AddStringAttachment($args['base64-attachment']);

$mail->MsgHTML($args['content']);

  if(strpos($args['to']['email'], ',')){
    $recipients = explode(',',$args['to']['email']);
    foreach($recipients as $v) $mail->AddAddress(trim($v), $args['to']['name']);  
  }else{
      $mail->AddAddress($args['to']['email'], $args['to']['name']);
  }

try {
  $mail->Send();
} catch (phpmailerException $e) {

} catch (Exception $e) {

}   
}

message.php file

    $imgdata = '...';//base64 image here
    $args['to']['name'] = 'John Smith';
    $args['to']['email'] = '[email protected]';

    $args['content'] = 'Image attached!';
    $args['from']['email'] = '[email protected]';
    $args['from']['name'] = 'Company name';
    $args['subject'] = 'Image';

    $args['base64-attachment'] = ($imgdata, 'Contract.png', 'base64', 'image/png'); //error with this line

    send_mail($args);

This won't send the mail and the attachment. Can someone help me? Thank you!

Upvotes: 0

Views: 3956

Answers (1)

hungrykoala
hungrykoala

Reputation: 1083

Change this:

$args['base64-attachment'] = ($imgdata, 'Contract.png', 'base64', 'image/png');

To this:

$args['base64-image']      = $imgdata;
$args['base64-attachment'] = "Contract.png, base64, image/png";

And we're gonna update this:

$mail->AddStringAttachment($args['base64-attachment']);

to this:

$attach_parameter = explode(",", $args['base64-attachment']);
$mail->AddStringAttachment($args['base64-image'], $attach_parameter[0], $attach_parameter[1], $attach_parameter[2]);

Or if it will always be a base64 image then you can just do it like this: You can also make Contract.png as a variable instead

$mail->AddStringAttachment($args['base64-image'], 'Contract.png', 'base64', 'image/png');

You can't just pass this ($imgdata, 'Contract.png', 'base64', 'image/png') directly as a parameter since the function will expect multiple variable as a parameter.

Upvotes: 1

Related Questions