views:

1608

answers:

1

I want to send an Newsletter with PHPMAiler. The newsletter does work, but I'm wondering if there is a better option to do this.

What I have is.

  1. HTML Page
  2. Images

Now my code looks as follows

$mail = new PHPMailer();

//Adding the body
$body = file_get_contents('template/index.htm');

$mail->Subject = "PHPMailer Test Subject via mail(), basic";

$mail->AltBody = "To view this message, please use an HTML compatible email viewer!";


$mail->SetFrom('xxxxxxx', 'xxxxxxxxxx');

$address = "[email protected]";
$mail->AddAddress($address, "xxxxxxx");

$mail->AddEmbeddedImage("template/images/bullet_point.gif","1");
$mail->AddEmbeddedImage("template/images/template_1_01.gif","2");
$mail->AddEmbeddedImage("template/images/template_1_03.gif","3");


$mail->MsgHTML($body);

if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

I use file_get_contents to get the html page, and AddEmbeddedImage to embed images, now is there a way to pass only the HTML page to PHPMailer and that PHP Mailer will embed these images automatically?

+1  A: 

I don't think what you are trying to do is possible (automatically adding required images) with PHPMailer "from scratch".

Maybe you could parse the HTML to get the list of images it links to ? There are at least 2 ways of doing that :

  • using rexexes ; generally not the best way to do things if you're trying to extract data from HTML -- and you are ^^
  • another (probably) better way would be using DOMDocument::loadHTML on the HTML content loaded from your file (the output of file_get_contents), and work with the methods of DOMDocument (and, why not, DOMXPath ?)

To get the images, I suppose you have <img> tags in your e-mail, with src attributes ; the goal is to find the values of those ones ;-)

Once you have the list of images path, you iterate over them, and call $mail->AddEmbeddedImage on each one of them.

I suppose that would work just fine (haven't tried though, but I don't see why it wouldn't).

As a side note, the other way would be to keep the images on your server for a couple of days/weeks/months, and not include them in the mail ; it would make the mails smaller, which means :

  • less bandwith spent on your side (if your are sending lots of mails, it can represent quite an amout of bandwith)
  • less bandwith spent on each one of your clients' side -- which is nice for them too ^^
  • less space used on their hard disks ;-)

And to make sure the images don't get erased / replaced on the server before a couple of weeks/month, you can create a new directory for each newsletter, containing it's images -- and once in a while, delete the directories older than X days.

Pascal MARTIN
Thanks for your valuable post!!!
Roland
you're welcome :-) Have fun !
Pascal MARTIN