go top

MEGA Sale

  • Colection of 65 PHP scripts for $4.29 each

Get 65 PHP scripts in a bundle for $4.29 each!

View Offer

How to send email with PHP

Tuesday, 6th December, 2011  /  PHP Tutorials  /  34 Comments
One thing you are definitely going to deal with, when programming in PHP is sending emails. Although it 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 everybody 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 equally 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 check if it is installed 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.
Share on:

34 Comments to "How to send email with PHP"

Goat

Goat / July 21, 2015 at 04:35 am

I have a wamp server does the mail function work if I execute it inlocal server?

Abdourahman

Abdourahman / April 23, 2015 at 11:04 am

just follow the details given in the code it will give u and idea on how to send mail

mahendra

mahendra / October 9, 2014 at 09:45 am

if user is sign up in oursite
then the verification mail is automatically send by that particular user's mail account.
means the entered email is correct or not

Raghavendra

Raghavendra / August 30, 2014 at 07:18 am

Sir,
I am getting the following error message,I am quite new to php and request any one to please guide me how I can correct this error message.

Failed to connect to mail.gmail.com:25 [SMTP: Failed to connect socket: php_network_getaddresses: getaddrinfo failed: Name or service not known (code: -1, response: )]

Thanks

Eva

Eva / July 23, 2014 at 02:40 am

I need an php mail sender to send directly in inbox. Daily I have to send about 500-800 mail, this contain different subjects, there are about 20-50 sent together. I don't use it for spam. I would to know if you can help me and how much that cost me?
Thank you!

Raj

Raj / June 4, 2014 at 17:44 pm

How will get email.php

dharm

dharm / March 28, 2014 at 15:27 pm

this is comment for mail function ..............

kadir

kadir / December 19, 2013 at 05:22 am

i want to make e-mail format

Rahul K A

Rahul K A / November 2, 2013 at 07:37 am

where is mail.php ?

Pete

Pete / October 9, 2013 at 00:35 am

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>

Add your comment

Captcha

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

    Log in to your account to post your comments. If you still haven't joined our community yet, 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

    Free Scripts

    Add great new functionalities to your website with our Free Scripts collection.


    Free scripts

    PHP Scripts

    Check our extensive collection of top-notch PHP Scripts that will enhance your website!


    Commercial PHP scripts