Working With PHP Mail Function

[printfriendly]

Working With PHP Mail Function

PHP Mail

Now it’s time to get a little more interactive with your users with e-mail. But we are not talking about standard e-mail, in which you write to your mother to tell her about the cool site you’ve been building. (You did tell her, didn’t you? She would be so proud.) We’re talking about sending out e-mails using PHP.

Specifically, this chapter covers:

❑ Sending a basic e-mail

❑ Sending an e-mail formatted with HTML

❑ Multipart messages

Setting Up PHP to Use E-mail

We aren’t going to delve too deeply into the setup of a mail server for PHP, but here are the basics.

If you are in a *NIX (UNIX, Linux, and so on) environment, you will most likely have sendmail installed on your server. If you are using a hosting service, check with your service provider to make sure sendmail or some equivalent is being used.

If you are not using sendmail, or you have Apache installed on a Windows server, you have a couple of choices. You can use your existing SMTP (Simple Mail Transport Protocol) service, or you can install a mail server such as Mailtraq on your computer. If you have questions or concerns about setting up or using a mail server, there are many online resources available to help you. We suggest using a search engine.

Once you have your mail server squared away, you’ll need to modify your php.ini. There are a couple of parameters you need to set. Of course, if you are using a hosting service, they should already have these parameters set up.

SMTP: Set this to the IP address or DNS name of your SMTP server. For example, if you have a mail server installed on the same server as your PHP server, you should be able to set SMTP to localhost. This applies to Windows installations only.

smtp_port: Set this to the port PHP uses to connect to the SMTP server. This applies to Windows installations only, and is valid for PHP version 4.3 and above.

sendmail_from: The From address used by default by the PHP mail() command.

sendmail_path: The path to the sendmail program (*NIX servers only). For most servers, this is usr/sbin/sendmail. That’s just about all there is to setting up PHP for e-mail. We will test to make sure it works correctly in the next section, “Sending an E-mail.” More information about setting up PHP for mail can be found at http://us3.php.net/manual/en/ref.mail.php.

Sending an E-mail

The actual method of sending an e-mail is quite simple. Of course, it can be made much more complex with the addition of headers, and sending HTML and images. However, we are going to start off with something simple.

Sending a Simple E-mail

This example is just about the simplest code you can write to send an e-mail. Of course, it’s not very flexible,

but it does demonstrate the mail() function quite well.

1. Start your favorite text/PHP/HTML editor. Notepad works just fine.

2. Enter the following code. Make sure you put your own e-mail address in as the first parameter:


<?php
mail("[email protected]", "Hello World", "Hi, world. Prepare for our arrival. We’re starving!");
?>]

 

3. Save the text file as firstmail.php and load it in your browser. You should see a blank page and should receive an e-mail shortly at the address entered as the first parameter. Pretty cool, huh? That’s all there is to it!

How It Works

The mail() function automatically sends an e-mail, using the following format:

mail(to, subject, message, headers, other_parameters)

The parameters headers and other_parameters are optional. If you want to send a message to multiple recipients, their addresses must be separated with a comma in the to parameter:


<?php

mail("[email protected], [email protected]", "Hi", "Whazzup??")

?>

We will cover the headers parameter soon. The other_parameters are beyond the scope of this book, but if you want more information about the mail() function, point your browser to www.php.net/manual/en/function.mail.php.

You may have noticed when receiving this e-mail that there was no From address (or, your service provider may have automatically put in a bogus address. Ours says “Nobody.” In the next example, you’ll see how to add a “From:” parameter to your e-mail, and you’ll collect information from the user before sending the e-mail. Let’s dig in!

Collecting Data and Sending an E-mail

We are going to create two Web pages, postcard.php and pc_sendmail.php. The file postcard.php will collect the data you are going to send. The file pc_sendmail.php will actually send the message, using the data you enter.

  1. Start up your favorite text/PHP/HTML editor, and enter the following code:

<html>
E-mail
<head>
<title>Enter E-mail Data</title>
</head>
<body>
<form name="theform" method="post" action="pc_sendmail.php">
<table>
<tr>
<td>To:</td>
<td><input type="text" name="to" size="50"></td>
</tr>
<tr>
<td>From:</td>
<td><input type="text" name="from" size="50"></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" size="50"></td>
</tr>
<tr>
<td valign="top">Message:</td>
<td>
<textarea cols="60" rows="10" name="message">Enter your message here</textarea>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Send">
<input type="reset" value="Reset the form">
</td>
</tr>
</table>
</form>
</body>
</html>

  1. Save the page as postcard.php. Note that postcard.php doesn’t actually have any PHP code in it. It simply collects the required data in an HTML form. You give it a .php extension in case you decide to add PHP code to it later (and you will).
  2. Start a new text document and enter the following code:

<html>
<head>
<title>Mail Sent!</title>
</head>
<body>
<?php
$to = $_POST["to"];
$from = $_POST["from"];
$subject = $_POST["subject"];
$message = $_POST["message"];
$headers = "From: " . $from . "r\n";
$mailsent = mail($to, $subject, $message, $headers);
if ($mailsent) {
echo "Congrats! The following message has been sent: <br><br>";
echo "<b>To:</b> $to<br>";
echo "<b>From:</b> $from<br>";
echo "<b>Subject:</b> $subject<br>";
echo "<b>Message:</b><br>";
echo $message;
} else {
echo "There was an error...";
}
?>
</body>
</html>

  1. Save this page as pc_sendmail.php. This second page will take the values entered into the firstpage, and send them in an e-mail.
  2. Load up the first page, postcard.php, in your browser, and enter some data. Make sure you use valid e-mail addresses so that you can verify their receipt. It should look something like

Figure 1-1.

  1. Click the Send button. A second page appears, similar to the one shown in Figure 1-2.

Dressing Up Your E-mails with HTML

Because you are creating a postcard application, sending plain-text e-mails just won’t do. You want to dress them up a bit, and make them look professional, yet attractive. So, let’s add a bit of HTML to your e-mail code to dress it up!

Sending HTML Code in an E-mail

First, let’s try a little experiment. This step isn’t vital, but it will help illustrate a later point about headers.

  1. Go to your email form and send another e-mail. This time, put someHTML in the message. An example would be:

<h3>Hello World!</h3><br>Prepare for our arrival.<br><br><b>We are starving!!!</b>

  1. When you have entered all relevant data in the form, click the Send button, and check your e-mail. It should look something like the e-mail  shown in Figure 1-4.

How It Works

Perhaps this heading should be “How It Doesn’t Work.” That’s because your e-mail client does not know that it has received HTML. Why? Because you didn’t tell it! In order for any HTML-capable client to display HTML, the client needs to be told that the incoming e-mail is going to have some HTML tags on it. Only then will it know how to properly display your message.

Sending HTML by Using Headers

You need a way for your e-mail to tell the client it contains HTML. This is accomplished by using headers. You already saw how we used headers to include a “From:” parameter. Now you are going to use a similar header to tell the client that the e-mail message contains HTML.

  1. Now create new file pc_sendmail2.php in your favorite text editor.
  2. Save as postcard.php file to postcard2.php and Change form action from pc_sendmail.php to pc_sendmail2.php in your postcard2.php file

<html>
<head>
<title>HTML Mail Sent!</title>
</head>
<body>
<?php
$to = $_POST["to"];
$from = $_POST["from"];
$subject = $_POST["subject"];
$message = $_POST["message"];
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n";
$headers .= "From: " . $from . "\r\n";
$mailsent = mail($to, $subject, $message, $headers);
if ($mailsent) {
echo "Congrats! The following message has been sent: <br><br>";
echo "<b>To:</b> $to<br>";
echo "<b>From:</b> $from<br>";
echo "<b>Subject:</b> $subject<br>";
echo "<b>Message:</b><br>";
echo $message;
} else {
echo "There was an error...";
}
?>
</body>
</html>
  1. Save the file.
  2. Load postcard.php into your browser and fill in the fields with appropriate information. Be sure to include some HTML in the message field, such as:

<h3>Hello World!</h3><br>Prepare for our arrival.<br><br><b>We are starving!!!</b>

  1. Click the Send button, and open your e-mail client to see the new message, which will look something like Figure 1-5.

 

Multipart Messages
You want to be able to send your postcards to anyone. However, some people don’t have HTML capabilities in their e-mail client. Therefore, you will send your postcards using both plain text and HTML.

Multipart Messages

In order to send messages with both plain text and HTML, you will use Mixed Messages. (Don’t worry. This is one time when it’s okay to send your significant other a mixed message.) Here’s how to do it:

  1. Create new file called postcard3.php and add form action pc_sendmail3.php.

<html>
<head>
<title>Enter Data</title>
</head>
<body>
<form name="theform" method="post" action="pc_sendmail3.php">
<table>
<tr>
<td>To:</td>
<td><input type="text" name="to" size="50"></td>
</tr>
<tr>
<td>From:</td>
<td>
<input type="text" name="from" size="50">
</td>
</tr>
<tr>
<td>CC:</td>
<td>
<input type="text" name="cc" size="50">
</td>
</tr>
<tr>
<td>Bcc:</td>
<td><input type="text" name="bcc" size="50"></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" size="50"></td>
</tr>
<tr>
<td valign="top">Message:</td>
<td>
<textarea cols="60" rows="10" name="message"
>Enter your message here</textarea>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Send">
<input type="reset" value="Reset the form">
</td>
</tr>
</table>
</form>
</body>
</html>

See the figure 1-6

  1. Create new file pc_sendmail3.php in your favorite text editor.

<html>
<head>
<title>Multipart Mail Sent!</title>
</head>
<body>
<?php
$to = $_POST["to"];
$cc = $_POST["cc"];
$bcc = $_POST["bcc"];
$from = $_POST["from"];
$subject = $_POST["subject"];
$messagebody = $_POST["message"];
$boundary = "==MP_Bound_xyccr948x==";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: multipart/alternative; boundary=\"$boundary\"\r\n";
$headers .= "CC: " . $cc . "\r\n";
$headers .= "BCC: " . $bcc . "\r\n";
$headers .= "From: " . $from . "\r\n";
$message = "This is a Multipart Message in MIME format\n";
$message .= "--$boundary\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: 7bit\n\n";
$message .= $messagebody . "\n";
$message .= "--$boundary--";
$mailsent = mail($to, $subject, $message, $headers);
if ($mailsent) {
echo "Congrats! The following message has been sent: <br><br>";
echo "<b>To:</b> $to<br>";
echo "<b>From:</b> $from<br>";
echo "<b>Subject:</b> $subject<br>";
echo "<b>Message:</b><br>";
echo $message;
} else {
echo "There was an error...";
}
?>
</body>
</html>

When you submit your mail it also send email to your given cc and bcc addresses

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.
One comment on “Working With PHP Mail Function
  1. Hello Sir,
    I need to configure this mail() with attachment.
    Is it possible to attach a file/folder/image with this mail function?
    Please describe the process.

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *