How To Send HTML Emails With PHP and Zend

Okay, so now that you have installed Zend we can begin playing with the framework. Although it’s not necessary for this tutorial I recommend you know Object Oriented Programming so that you can better understand what’s going on.

To send text and HTML emails with Zend we are going to need two classes, the email validation and email classes, so include those in your script with the following lines.

// include mail class
require_once 'Zend/Mail.php';
// create mail object
$mail=new Zend_Mail();
// include validate class
require_once 'Zend/Validate/EmailAddress.php';
// create validate email object
$validator=new Zend_Validate_EmailAddress();

The email validation class comes with the “isValid” function, this function takes the email string as parameter and returns a true if the email is valid and a false if the email is invalid. If invalid, you can use this class’ “getMessages” function, which returns an array of messages.

One thing I like about this validation class and of Zend in general, is that the error messages were written down in a form that your users will understand, so you don’t to worry about “translating” them.

This are the error messages for the string “someone@somedomain” for example.

‘somedomain’ is not a valid hostname for email address ‘someone@somedomain’
‘somedomain’ does not match the expected structure for a DNS hostname
‘somedomain’ appears to be a local network name but local network names are not allowed

Now that I explained what the function we are going to use do, let’s use them!

if($validator->isValid($_POST['email']))
{
// valid email

}
else
{
// invalid email
	foreach($validator->getMessages() as $errorMessage)
	{
		echo "$errorMessage<br/>";
	}
}

At this stage, you know that this script receives an “email” string from a form that had an <input type=”text” name=”email” /> field, so am not going to talk about the form for now just the script that receives the form’s contents.

As you can see, we used the “isValid” function with the $validator object we created and the parameter $_POST['email'] to verify the email, if the email is valid we’ll send the email, if not (else) we’ll output the errors.

Let’s talk about the “else” part of this snippet. You might not have heard of the foreach function, the “getMessages()” function is an array of messages so we have used the “foreach” function and assigned the values of each array key to the variable $errorMessages in a loop until we run out or have gone through each array key, and until that happens we echo the values of $errorMessages, ” ‘somedomain’ does not match the expected structure for a DNS hostname” for example.

Now let’s fill in the part of the snippet if the message is valid that’s after “// valid email”

// valid email
        // text only option
	$mail->setBodyText(strip_tags($_POST['message']));
	// html option
	$mail->setBodyHtml($_POST['message']);
        // sender ino
	$mail->setFrom($_POST['email'],$_POST['name']);
        // receiver info
	$mail->addTo('miguel@webhole.net','Miguel Alvarez');
        // subject
	$mail->setSubject('WebHole | Contact Form');
	// send email
	$mail->send();
        // success response
        echo "Message sent";

As you can see we are using the “mail” object we created. Let’s talk about the first two function we use “setBodyText” and “setBodyHtml”. As you might know, some people have their email set to read text mail only while others don’t care or prefer HTML. So what we are doing with these two function is giving people alternative mime types “setBodyText” for text-only email and “setBodyHtml” for emails that contain HTML code.

Notice that I also used the strip_tags function,you can do any other validation you want, that’s because if you don’t strip the tags Zend will send the text as it is, which means that if your message contains a link tag “<a href=”http://domain.com/”>Domain</a>”, the text-only message will display the message with the symbols and everything. You can also strip certain tags from the HTML email just like would regularly.

The “setFrom” function takes two parameters the sender’s email first and then the sender’s name. The “addTo” function also takes two parameters, the recipient’s email and then the recipient’s name, the “setSubject” takes the subject of the email and finally, after you have set the email components you can send the email with the “send” function and display a success message.

So to sum it all up, let’s make quick form ( form.html ), which you can use with the script we just made which we’ll call “zendScript.php”

<form action="zendScript.php" method="post" >
<label>Name</label>
<p><input type="text" name="name" /></p>
<label>Email<sup>*</sup></label>
<p><input type="text" name="email" /></p>
<label>Message<sup>*</sup></label>
<p><textarea name="message";>
</textarea></p>
<input type="submit" value="send" id="button" />
</form>

and this will be the zendScript.php contents.

isValid($_POST['email']))
{
// valid email

	// text only option
	$mail->setBodyText(strip_tags($_POST['message']));
	// html option
	$mail->setBodyHtml($_POST['message']);

	$mail->setFrom($_POST['email'],$_POST['name']);
	$mail->addTo('miguel@webhole.net','Miguel');
	$mail->setSubject('WebHole | Contact Form');
	// send email
	$mail->send();
	//
        echo 'message sent';
}
else
{
// invalid email
	foreach($validator->getMessages() as $errorMessage)
	{
		echo "$errorMessage<br/>";
	}
}

?>

This is really nothing compared to what Zend can really do, for example you can check not only the if the email’s format is valid but also if the email really exists. You can find out more here http://framework.zend.com/manual/en/zend.mail.html

blog comments powered by Disqus