How to send email with PHP

posted on November 19, 2008, 4:32 pm

One thing you are definitely going to deal with, when programming in PHP is sending emails. Although is seems like a very trivial and easy to accomplish task sometimes there can be unexpected obstacles.

First of all we will start with the most common way to send plain text email. I'm pretty sure everobody is familiar with the mail() function.

<?php 
$To = 'recepient@yourdomain.com'; 
$Subject = 'Send Email'; 
$Message = 'This example demonstrates how you can send plain text email with PHP'; 
$Headers = 'From: sender@yourdomain.com \r\n' . 
'Reply-To: sender@yourdomain.com \r\n' . 
'Content-type: text/html; charset=UTF-8 \r\n'; 
 
mail($To, $Subject, $Message, $Headers); 
?>

The parameters of the mail() function are pretty much self-explanatory. The only thing here that can cause confusion is the "Content-type" header. Content-Type states what sort of content is the email message. It can be text, html, file, image and many others. The "Content-type" header may also contain information about the character encoding.

Now we will send another email, but this time we will add attachment to it. The idea is much the same, only the headers have to be set.

<?php 
$b = 0; 
$mail_attached = ""; 
$boundary = md5(time()); 
$fp = fopen($file_name,"rb"); 
$content[$b] = fread($fp,filesize($file_name)); 
$mail_attached .= "--" . $boundary . "\n" 
. "Content-Type: binary/octet-stream; name=\"basename($file_name)\" \n" 
. "Content-Transfer-Encoding: base64 \n" 
. "Content-Disposition: inline; filename=\"basename($file_name)\" \n\n" 
. chunk_split(base64_encode($content[$b]))." \n"; 
$b++; 
fclose($fp); 
$mail_attached .= "--".$boundary." \n"; 
 
$add_header = "MIME-Version: 1.0\n". 
"Content-Type: multipart/mixed; boundary=\"$boundary\"; Message-ID: <".md5($email_from).">"; 
$mail_content = "--".$boundary."\n". 
"Content-Type: text/plain; charset=\"UTF-8\"\n". 
"Content-Transfer-Encoding: 8bit \n\n". 
$msg." \n\n". 
$mail_attached; 
mail($email_address, $subject, $mail_content, "From: ".$email_from."\nCC: ".$email_cc."\n
BCC: ".$email_bcc ."\n Errors-To: ".$email_from."\n".$add_header); 
?>

First of all we need to create a unique string, for our email message, which we call boundary string. Our file data must be between those boundary string, so that it can be identified as file by email programs. We use md5 ot the current time. Then we have to add our file. We read its contents and load it into string. Than we have to encode it with base64_encode function and split it to smaller pieces of data. These chunks of data are required by the MIME type specifications. Now we close the boundary string. The only thing left is to add our message to this email.

We are done sending emails with mail() function. Although it is very easy the mail function doesn't provide us a way to send emails using SMTP authentication. Many of today's Mail servers require this kind of authorization and it is important that you know how to handle this.

Fortunately there is an equaly easy way to send email from PHP script using SMTP authentication. All you have to use is PEAR Mail Package. It is distributed along with PHP itself, so you just have to ckech if it is istalled on your system. If it is, the only thing you have to
do is to set up the required parameters for an SMTP authentication.

<?php 
include_once("Mail.php"); 
 
$From = "Sender's name <sender@yourdomain.com>"; 
$To = "Recipient's name <recipient@yourdomain.com>"; 
$Subject = "Send Email using SMTP authentication"; 
$Message = "This example demonstrates how you can send email with PHP using SMTP authentication"; 
 
$Host = "mail.yourdomain.com"; 
$Username = "smtp_username"; 
$Password = "smtp_password"; 
 
// Do not change bellow 
 
$Headers = array ('From' => $From, 'To' => $To, 'Subject' => $Subject); 
$SMTP = Mail::factory('smtp', array ('host' => $Host, 'auth' => true, 
'username' => $Username, 'password' => $Password)); 
 
$mail = $SMTP->send($To, $Headers, $Message); 
 
if (PEAR::isError($mail)){ 
echo($mail->getMessage()); 
} else { 
echo("Email Message sent!"); 
} 
?> 

As you can see in the example above, you have to include the PEAR Mail package, so your script can use it. It has to be done only once, so we use include_once. Then you have to put your data in the fields and that's it. What the rest of the code does is create a new SMTP object, using the data you entered and send the email.

Comments
Spowart posted on June 8, 2009, 2:43 pm
How would the form be changed to allow for "PHP script using SMTP authentication" to be used with a HTML entry form "<form>" etc. I need to be able to have a contact form my webpage, instead of defining the message in the script. need something along the lines of a variable. "$message = $_POST["message"];" not sure how to code any of this.. Please help thanks

JT posted on February 16, 2009, 1:46 pm
I installed PEAR successfully and simply copied and pasted your above sample code to test (with just an adjustment to the include path to point to a local copy of the mail.php file). It worked perfectly. However, three days later, I tried to run it again, and now I'm getting this error:

Fatal error: Class 'Mail' not found in C:wampwwwPEARmail.php on line 26

I have no idea what changed to make that happen and it's been driving me nuts. Do you have any suggestions?

elxatz posted on January 8, 2009, 4:49 pm
I use the third box to send an e-mail, but i write my message in Greek language and is not appear correctly.. should i write an encoding tag? but i don't know where...
Thanks!!
---------
Veselin: what third box are you talking about?

selom posted on January 7, 2009, 4:31 pm
happy new year and thank you very much for this helpful page.my problem is I've been trying for a while to figure out how to configure the php.ini to be able to sent a mail. i will appreciate it if you can help me out.thank you in advance.

Pages:   1   
   
If you have any additions, suggestions or modifications for this example please contact us or use the form below.
   
Your name:
Your email: (email address will not be posted on the web site)
Comment:
Verification