php email using mysql, html and imbedding images
I need to send a daily email based on data in mysql database which updates every day. I need it to be in html so that I can put links in there. I will also use images in the email. The basic structure will be:
Here's the list:
Business name (which is a link) Short description Image (which is a link)
Business name (which is a link) Short description Image (which is a link) . . .
All the data is in mySQL database (although the "image" in the database is a reference to a file eg /images/business/image.jpg)
My questions is should I be using phpmailer (I've never used it before) or using something like this:
//set up msg
$msg = "<html><body>Here's the list: <br /><br />";
while($i<numofelementsindb){
$business=mysql_result($result, $i,"business");
$description=mysql_result($result, $i,"description");开发者_高级运维
$msg .= "The business name is <a href='www.example.com'><b>{$business}</b></a> does {$description}<br />\r\n";
$i++;
}
$msg .= "</body>
</html>";
//send
I also don't know how to imbed the image in the email either so any advice would be appreciated.
Do you have any safety suggestions as well?Thanks
Using a mime email class I've written, here's the code to do what you wanted:
require 'class.omime.php';
$email = new omime('related');
$html = "<html><body>Here's the list: <br /><br />";
while($i < numofelementsindb) {
$business = mysql_result($result, $i,"business");
$description = mysql_result($result, $i,"description");
$imageFilePath = ''; # path to image file
$cid = $email->attachFile($imageFilePath);
$html.= "The business name is <a href='www.example.com'><strong>{$business}</strong></a> does {$description}<br />\r\n";
$html.= "<img src=\"cid:{$cid}\" alt=\"Image of {$business}\"/><br /><br />\r\n";
$i++;
}
$html.= "</body></html>";
$email->attachHTML($html);
$email->send('recipient@email.com', 'Daily List of Businesses', 'from: sender@email.com');
All the images will be attached with the email so you won't have to place them on a webserver. Recipient will still be asked if they want to display the images. Check the omime source page if you're interested.
I suggest using phpmailer, for it has ready method for almost anything you need. Nonetheless, you can also use the simple php mail() function, but be aware that if you want an html mail you need to specify the MIME and content type in the headers, or it wont' work (it will display the tags as is).
$header = 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
Images can be embedded the same way you do in a web page (<img src=....
); keep in mind that many mail viewer are configured to not load images in e-mail bodys by default, asking users to load them only if they want. And be very sure about the origin of those images, for they are subject to xss vulnerability if they come from users. In that case escape before outputting to html.
精彩评论