Sending Email with PHP Networking

In this article we will look at the protocol that is involved in sending email messages. We will also examine the thorny issue of how to send an attachment with an email message. This article is the second of two parts.

Setting up PHP to send email

Before we do anything else, let’s enable PHP to send email. This is a very simple process. Open up your configuration file and go to the section that deals with emailing. To save time, open up the find dialog box and enter "mail." This will take you to the mail section of the configuration file. It looks something like this:


[mail function]

; For Win32 only.

SMTP = localhost

smtp_port = 25


; For Win32 only.

;sendmail_from = me@example.com


; For Unix only. You may supply arguments as well (default: "sendmail -t -i").

;sendmail_path =


You need to change the first two settings here, like so:


SMTP = my.mailserver.com


This is where you put the name of your outgoing mail server.

The second setting is the return address that is sent with all your email messages, so change it to whatever email address you want there:

; For Win32 only.

;sendmail_from = myreturn@emailaddress.com


These two settings are for Windows users. The third option is for Unix systems, as indicated in the configuration file. The default settings are usually correct and work most of the time. If these settings don’t work, then your system or network administrator will be able to help.

That’s about it. So how does PHP help in sending email messages? PHP provides a function called mail(). This function takes the following arguments:

  • To – this is the email address to which the message goes.

  • subject – subject of the message.

  • Message – the actual message goes here.

  • Headers (optional) – Any extra headers, such as from, CC and BCC.

The functions returns true if the message has been accepted for delivery and false if not. In its simplest form, you use the mail() function like so:



<?php

$to = " esme@holidays.com ";

$subject= "Lunch?";

$message = "This is my first test of the mail() function.";

// Send

$result=mail($to,$subject, $message);

?>




With Headers it would look something like this:


<?php

$to = " esme@holidays.com ";

$subject= "Lunch?";

$message = "This is my first test of the mail() function.";

$headers = ‘From: webmaster@example.com’ . "rn" .

çc: webmaster@example.com’ . "rn" .

bcc: ac@milan.com;


$result=mail($to, $subject, $message, $headers);

?>


{mospagebreak title=Sending mail with PHP}

Now that we know what tools PHP provides, let’s write a quick application that will help us send messages with attachments. In order to send a message with an attachment, you need to send a mail header instructing that the email be sent as an attachment. A header might look like this:


Content-disposition: attachment; filename=myfile.doc


The header instructs the email to send the message as an attachment with a file called myfile.doc. So if you want to send a short message with an attachment, this is how it could look:


<?php

$to = " esme@holidays.com ";

$subject= "Lunch?";

$message = "This is my first test of the mail() function.";

$headers = "Content-disposition: attachment;

filename=myfile.docn";

$headers .= "cc:salles@mycompany.comn";

$result=mail($to, $subject, $message, $headers);

?>

Another very important step that you need to take when sending attachments is to set the content type for the file. The following are the available content types:

  • image/gif
  • image/jpeg
  • audio/x-wav
  • audio/vnd.rn-realaudio
  • video/mpeg
  • video/avi

You also may want to send application files. Some are text files, and some are binary files. For example, an RTF file is a text file, whereas a Word document is a binary file. Generally binary files are of type applica/octed stream. Binary files require encoding when they are sent through an email. PHP provides us with a function called chunk_split(), that does just that:


$encode = chunk_split(base64_encode($string));


In addition, when sending an encoded file, you need to inform the mail software that you intend to sent a encoded file. This is done in the headers section of the mail function:


Content-Transfer-Encoding: base64

{mospagebreak title=Application Code}

In our application we will be creating a form that will collect the mail data for us, then we will process and send the data over to the mail function, which will then send the mail message. Below is the code that makes up our very simple demonstration application:


<?

//is form submitted

if(isset($_POST['key'])){

//collect the information

$from=$email;

$cc=$_POST['cc'];

$bcc=$_POST['bcc'];

if(empty($_POST['tos'])){

$error=true;

}else{

$to=$_POST['tos'];

}

if(empty($_POST['sub'])){

$error=true;

}else{

$subject=$_POST['sub'];

}

if(empty($_POST['msg'])){

$error=true;

}else{

$msg=$_POST['msg'];

}

//check if the an attachment is present

if(isset($_FILES['userfile']['name'])){

$attachment = $_FILES['userfile']['tmp_name'], $_FILES['userfile']['name'];

$headers ="Content-disposition: attachment;

$filename=.$attachment."n";

$headers=.Content-Transfer-Encoding: base64n";

}

if(!$error){

$res=mail($to,$subject,$msg,$headers);

}

if(!$res){

echo "Mail error occurred";

}

}


?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Untitled Document</title>

</head>


<body>

<span class="style2">Sending Mail With PHP</span>

<form name="form1" method="post" action="newmsg.php">

<table width="100%" border="0" class="block">

<tr>

<td width="10%" valign="top"><strong>To</strong></td>

<td width="90%"><input name="tos" type="text" id="to" size="70" value="esme@holidays.com"/></td>

</tr>

<tr>

<td valign="top"><strong>Cc</strong></td>

<td><input name="cc" type="text" id="cc" size="70" /></td>

</tr>

<tr>

<td valign="top"><strong>Bcc</strong></td>

<td><input name="bcc" type="text" id="bcc" size="70" /></td>

</tr>

<tr>

<td valign="top"><strong>Subject</strong></td>

<td><input name="sub" type="text" id="sub" size="70" />

<input type="hidden" name="hkey" /></td>

</tr>

<tr>

<td valign="top"><strong>Attachment</strong></td>

<td>

<input name="userfile" type="file" id="userfile" size="70" /></td>

</tr>

<tr>

<td valign="top"><strong>Message:</strong></td>

<td><label>

<textarea name="msg" cols="50" rows="10"></textarea>

</label></td>

</tr>

<tr>

<td>&nbsp;</td>

<td><input type="submit" name="submit" value="Send Message" />

</td>

</tr>

</table>

</form>

</body>

</html>


The code above produces the following form:


{mospagebreak title=Code Examined}

Let’s take a look at the code. First we check to see if the form was submitted:


<?

//is form submitted

if(isset($_POST['key'])){


 

Then we collect the form data and store it in shorter variables:


//collect the information

$from=$email;

$cc=$_POST['cc'];

$bcc=$_POST['bcc'];


 

The next step is to filter the data and set the error message for each of the required fields:


if(empty($_POST['tos'])){

$error=true;

}else{

$to=$_POST['tos'];

}

if(empty($_POST['sub'])){

$error=true;

}else{

$subject=$_POST['sub'];

}

if(empty($_POST['msg'])){

$error=true;

}else{

$msg=$_POST['msg'];

}



Finally we test to see if the user wants to send an attachment. The attachment is sent through the $_FILES[''] array. If the file is loaded, we set the headers for the mail function. Notice that the content-disposition and content-transfer-encoding has also been set:


//check if the an attachment is present

if(isset($_FILES['userfile']['name'])){

$attachment = $_FILES['userfile']['tmp_name'], $_FILES['userfile']['name'];

$headers ="Content-disposition: attachment;

$filename=.$attachment."n";

$headers=.Content-Transfer-Encoding: base64n";

}




If there are no errors, the code continues to send the email message with or without the headers:


if(!$error){

if($headers <> ""){

$res=mail($to,$subject,$msg,$headers);

}else{

$res=mail($to,$subject,$msg);

}

}



Finally, an error check is made to inform the user if any errors occurred.



if(!$res){

echo "Mail error occurred";

}

}


?>


{mospagebreak title=Sending Mail using the PEAR::Mail}

While using PHP’s mail() function makes it relatively easy for us to send mail, it lacks certain things. One of these is the validation of an email address. In other words it does not check to see if an email address is valid before sending mail.

This particular functionality is incorporated into PEAR’s mail class. To use this class you need to have PEAR installed and you also need to download the mail package. If this package is already in your pear directory, you simply run the following command in your shell or DOS prompt:


pear install mail


If the installation was successful you will get an "installation OK" message. You can also verify if the package was installed by running the following command:


pear list


This will give you a list of all the installed packages. It looks something like this:



Now you can use the class like so:


<?php

require "Mail.php";

$to = array("nita@mysite.com");

$headers = array(

‘From’ => "duimpie@hissite.com",

‘Cc’ => "xuros@siteways.com",

‘Subject’ => "Using PEAR::Mail to send email"

);

$body = <<< BODY

Hi Nita,

Just testing how to send email from a PHP script with the PEAR::Mail class.

Your eager to learn friend

Duimpie

BODY;

$mail = Mail::factory(‘mail’);

$mail->send($to, $headers, $body);

?>


The code above simply sends a plain text message with headers. It uses the built-in mail() function to send the message. Notice the line highlighted in red, particularly the word factory. The PEAR::Mail class has multiple factories to choose from (mail, sendmail, and smtp). Those of you who use object-oriented programming will know that it uses factories to load and implement different technologies with the same application programming interfaces (APIs). In the case of the Mail() class, you can load the class elements needed to communicate with the mail server when the Mail object is created. The elements do the following:

  • The mail factory – uses the built-in mail() function to send email.

  • Sendmail factory – initiates communication directly with the sendmail program.

  • Smtp factory – uses sockets to connect directly to the server. It also supports authentication, which of course allows for secure communication.

For more complicated mail messages, PEAR provides a Multipurpose Internet Mail Extension (or MIME as is commonly known) class that allows you to build HTML mail messages. The class itself is called PEAR::Mail_mime and is used like so:


<?php

require "Mail.php";

require "Mail/mime.php";


$to = array("nita@mysite.com");

$headers = array(

‘From’ => "duimpie@hissite.com",

‘Cc’ => "xuros@siteways.com",

‘Subject’ => "Using PEAR::Mail to send email"

);

$mime = new Mail_mime();

$txtBody = <<< BODY

Hi Nita,

Just testing how to send email from a PHP script with the PEAR::Mail class.

Your eager to learn friend

Duimpie

BODY;

$mime->setTXTBody($txtBody);

$htmlBody = <<< BODY

<html><body>

<h1>Hi Nita,</h1><br>

Just testing how to send email from a PHP script with the PEAR::Mail class.

Your eager to learn friend

Duimpie

<br>

</body></html>

BODY;

$mime->setHTMLBody($htmlBody);?>

$body = $mime->get();

$headers = $mime->headers($headers);

$mail = Mail::factory(‘mail’);

$mail->send($to, $headers, $body);


The code above has the same basic structure as the previous example, except for the HTML formatting. It also has a plain text version. This is so that your message is sent through even if the receiving server does not accept HTML messages.

Google+ Comments

Google+ Comments