Sending emails the right way – using PHPMailer and email templates

Sending emails the right way - using PHPMailer and email templatesWhen sending mail in PHP its always best to use an SMTP server rather than the mail() function, and the ideal candidate for the job is PHPMailer.

Assuming you have an SMTP server (usually mail.yourdomain.com) and a username and password (to authenticate as some servers won’t allow you to send via SMTP without it) sending mail with PHPMailer is easy as pie.

For websites that send lots of emails with different information it’s a good idea to setup some email templates.

In this example we will create a folder called “email_templates” and will create a file called “register.html” which will contain the login information when someone registers to our site:

<html>
<body>
<h1>Account Details</h1>
<p>Thank you for registering on our site, your account details are as follows:<br>
Username: %username%<br>
Password: %password%
</p>
</body>
</html>

Now here is the code to send this as an email, assuming you have the username and password of the user signed up.

<?php
// Include the PHPMailer class
include('PHPMailer/class.phpmailer.php');

// Retrieve the email template required
$message = file_get_contents('email_templates/register.html');

// Replace the % with the actual information
$message = str_replace('%username%', $username, $message);
$message = str_replace('%password%', $password, $message);

// Setup PHPMailer
$mail = new PHPMailer();
$mail->IsSMTP();

// This is the SMTP mail server
$mail->Host = 'mail.yourdomain.com';

// Remove these next 3 lines if you dont need SMTP authentication
$mail->SMTPAuth = true;
$mail->Username = 'admin@yourdomain.com';
$mail->Password = 'blah';

// Set who the email is coming from
$mail->SetFrom('admin@yourdomain.com', 'Website Admin');

// Set who the email is sending to
$mail->AddAddress('user@gmail.com');

// Set the subject
$mail->Subject = 'Your account information';

//Set the message
$mail->MsgHTML($message);
$mail->AltBody(strip_tags($message));

// Send the email
if(!$mail->Send()) {
 echo "Mailer Error: " . $mail->ErrorInfo;
}
?>

Quick way to INSERT an array into a table

This is a useful function that I wrote to insert an array into a table in your database.

function insert_array($table, $data) {  
 $cols = '(';
 $values = '(';
 foreach ($data as $key=>$value) {
  $value = addslashes($value);
  $cols .= "$key,";  
  $values .= "'$value',";  
 }
 $cols = rtrim($cols, ',').')';
 $values = rtrim($values, ',').')';  
 $sql = "INSERT INTO $table $cols VALUES $values";
 mysql_query($sql) or die(mysql_error());
 return mysql_insert_id();
}

Here is an example of using this code:

<?php
$arr = array('title' => $_POST['title'], 'product_code' => $_POST['product_code'], 'description' => $_POST['description'], 'price' => $_POST['price']);
$product_id = insert_array("products", $arr);
?>

Create bit.ly links automatically

Create bit.ly links automaticallyFirst things first get yourself signed up on bit.ly to receive an API key.

Once you have signed up you can use this PHP function to create links automatically (you will need to provide the bit.ly username and API key as well as the URL).

function create_bitly_link($apikey, $username, $url) {
 $ch = curl_init("http://api.bit.ly/shorten?version=2.0.1&longUrl=".urlencode($url)."&login=".$username."&apiKey=".$apikey);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
 curl_setopt($ch, CURLOPT_TIMEOUT, 15);
 $data = curl_exec($ch);
 curl_close($ch);
 if (preg_match('/<shortUrl>(.+?)<\/shortUrl>/is', $data, $m)) {
  return $m[1];
 }
 else {
  return false;
 }
}

Fancybox jQuery lightbox

Fancybox jQuery lightboxFancyBox is a tool for displaying images, html content and multi-media in a modal window (lightbox) based on the jQuery library.

What I love about FancyBox is loading new windows in an iframe. For example one website that I built used the RPX system allowing users to log in via their favorite social networking site. Rather than just redirect users to the RPX page I had it load in a modal window so they were never taken away from my site.

$(document).ready(function(){
 $('a.iframe').fancybox({
  'frameURL': 'https://XX.rpxnow.com/openid/embed?token_url=XX',
  'frameHeight': 280,
  'hideOnContentClick': false
 });
});

Hello world

Welcome to the new XEWeb website, we will be updating the blog as much as we can with juicy topics and code snippets.

Please feel free to subscribe to our RSS feed, join our community forum or follow us on twitter.