I searched for a simple solution to send some personalized html e-mails with embedded pictures. However I didn’t find one. Thus I created the following script:

<?php
require 'class.phpmailer.php';

foreach(file('recipients.csv') as $line)
{
    list($to, $name, $greeting) = explode("\t", $line);
	$mail = new PHPMailer;

	$mail->setFrom('no-reply@example.net', 'Example Sender');
	$mail->CharSet = 'utf-8';
	$mail->SetLanguage ("en");
	$mail->isHTML(true);

	$mail->addAddress($to, $name);
	$mail->Subject = "Example Newsletter";

	$mail->AddEmbeddedImage('test.png', 'test');

	$body = "<html>
  		<head>
    			<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">
  		</head>
  		<body>
    		<p>$greeting $name</p>
		<p>This is a personalized newsletter</p>
		<p>Nice picture <img alt=\"Example Pic\"
                  src=\"cid:test\"
                  height=\"424\" width=\"300\"></p>
		</body>
		</html>";

	$mail->Body = $body;

	if(!$mail->send()) {
	    echo 'Message could not be sent.';
	    echo 'Mailer Error: ' . $mail->ErrorInfo;
	} else {
	    echo 'Message to ' . $to . " has been sent\r\n";
	}
}
?>

It uses phpmailer and a simple csv-file to generate and send the emails. To execute it you just need to upload it to a server and execute it with:

php sendnewsletter.php

To add new recipients you can open the file recipients.csv in Microsoft Excel or LibreOffice and add new rows. When you save it just select the CSV-Format and choose the tabulator character as deliminator.

The generated email in this example looks like this:

It can be freely adapted in the code. You just need to escape ” with \”

Download the code

Leave a comment

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