« Reading files with PHPRSS Parsing using Pear »

How to send email with PHP Posted in PHP Tutorials | 28 Comments
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"
. 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." nn".
$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.

Do you know PHP / HTML / CSS / JS well?

Write tutorial on a topic you are good in and become a trusted PHP jabber! Share your knowledge with thousands of webmasters and we will reward you for your generosity by giving you bonus points which you can use as a voucher to buy any of our commercial products. Read more about our reward program.

28 Replies to "How to send email with PHP"

dharm March 28, 2014 at 3:27 pm | Reply

+2

this is comment for mail function ..............
kadir December 19, 2013 at 5:22 am | Reply

0

i want to make e-mail format
Rahul K A November 2, 2013 at 7:37 am | Reply

+4

where is mail.php ?
Pete October 9, 2013 at 12:35 am | Reply

0

Dear Sir/Madam

Its a pleasure to have this chance of communicating to you. Well I am kindly requesting members to write for me the mail.php code for the form below. I am eagerly waiting for it. Thank you. If anyone has the result kindly send it to the email above please.

<div style="height:15px"></div>
<form action="mailse.php" method="post">
<div>
<div align="left">
<input class="input_txt2" value="Name:" name="Name2" type="text" />
</div>
</div><div style="height:5px"></div>
<div>
<div align="left">
<input class="input_txt2" value="E-mail:" name="Name" type="text" />
</div>
</div><div style="height:5px"></div>
<div>
<div align="left">
<input class="input_txt2" value="Subject:" name="Name" type="text" />
</div>
</div><div style="height:5px"></div>
<div>
<div align="left">
<textarea class="text_area2" cols="32" rows="3" name="Message">Message:</textarea>
</div>
</div><div style="height:8px"></div>
<div><input class="submit2" name="Submit2" type="submit" value="Submit" />
<input class="submit2" name="Submit3" type="reset" value="Reset" />
</div>
</form>


</div>
brian August 2, 2013 at 10:14 am | Reply

+3

How do i send sms to a mobile phone using php?
Raja_appiev March 10, 2014 at 8:06 am

0

How do i send sms to a mobile phone using php???
swaroop July 24, 2013 at 9:59 am | Reply

+4

please help me how can i send email automatically every day by using threads in php
Arun June 27, 2013 at 5:21 pm | Reply

+2

Hi,
I am using 'simple php form mailer'.
It has captcha but not SMTP authentication.
Can you please modify the script for me?
Thanks and regards,
Arun
arfiandi May 9, 2013 at 1:58 pm | Reply

+2

how do i check if i have "mail.PHP" or where do i get one?
David Johnson March 14, 2013 at 11:01 pm | Reply

+1

Can someone here please help me with an email that came with flash template. it is called "send.php" I am confused whether I make changes to certain areas or not! I get error message no matter what I do!

My personal email is: elambstudio@gmail.com

David
Tom December 8, 2012 at 11:06 am | Reply

+4

Hi, hope you can help, can I send you my php code that actualy works pretty good with the mail() function but i need to do this from a smtp authitication, no I just need to no where in my code must I place the relevant username and password detail
Tom December 8, 2012 at 12:42 pm

+1

Can I place my PHP code her for help, i got it to work perfectly on servers without smtp authentication, but now Im not sure where to place the code in my exsisting php code, I have a html form sending the detail to the php is all validations are correct the php reponse with html included below the php code and I would like to keep the same way. Please bear with me as I am new to PHP


Please be polite and helpful and do not spam or offend others. We promise you will be treated the same way.

Log in your free account or if you still haven't joined our Webmaster Community Reward Program, you can create your free account now.

Posting tip:
if you use code in your comments please put it in these tags [php], [sql], [css], [js]
PHP code example: [php] echo date("Y-m-d"); [/php]

Thank you,
~ PHPJabbers team ~