PHP for Beginners: Part 3 – Email with PHP

Posted in Tutorials3 years ago • Written by 6 Comments

Today We are continuing our PHP series. One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. In this part I will show you how to send e-mail messages using PHP.

For those who missed the previous parts:

Part 1

Part 2

 

PHP mail() function

E-mails in PHP can be easily sent using the library function ‘mail’. This function takes four arguments to send E-mails from a PHP web page and returns ‘true’ upon successful delivery of Email. The parameters of this function are as follows:

  • Recipient E-mail address
  • E-mail Subject
  • E-mail message (body)
  • Headers and additional parameters

Syntax:

mail( string to, string subject, string message [, string additional_headers [, string additional_parameters]] );

The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an e-mail ( Sender E-mail address ) but you can also include other headers like cc and bcc.

This function returns the boolean value ‘True’ if the mail is sent successfully, otherwise it returns ‘False’.

Sending An E-mail

Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message:

$to = "[email protected]";
$subject = "PHP Rock";
$body = "PHP is one of the best scripting languages around";
$headers = "From: [email protected]\n";
mail($to,$subject,$body,$headers);
echo "Mail successfully sent to $to";

This code will actually do two things. Firstly it will send a message to [email protected] with the subject ‘PHP Rock’ and the text:
PHP is one of the best scripting languages around
and the e-mail will be from [email protected] It will also output the text:
Mail successfully sent to [email protected]
to the browser.

Formatting E-mail

Something you may have noticed from the example is that the From line ended with \n. This is actually a very important character when sending e-mail. It is the new line character and tells PHP to take a new line in an e-mail. It is very important that this is put in after each header you add so that your e-mail will follow the international standards and will be delivered.

The \n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.

PHP Validate Email

PHP validate email script is an easy way to validate an email address. Use this quick and simple PHP regular expression for email validation. This is also case-insensitive, so it will treat all characters as lower case. It is a really easy way to check the syntax and format of an email address. Function will return TRUE if address is valid and FALSE if not.

function isValidEmail($email){
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

Mail Without Variables

The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could also have been done on one line using text like this:

mail("[email protected]","PHP Rock","PHP is one of the best scripting languages around","From: [email protected]\n");

But that would make your code slightly harder to read.

Error Control

As anyone who has been scripting for a while will know, it is extremely easy to make mistakes in your code and it is also very easy to input an invalid e-mail address (especially if you are using your script for form to mail). Because of this, you can add in a small piece of code which will check if the e-mail is sent:

if(mail($to,$subject,$body,$headers)) {
echo "An e-mail was sent to $to with the subject: $subject";
} else {
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid";
}

This code is quite self explanatory. If the mail is sent successfully it will output a message to the browser telling the user, if not, it will display an error message with some suggestions for correcting the problem.

BONUS: Sending Email Using the Zend Framework

In addition to my previous Zend Framework tutorials, in this section i will introduce you another cool feature of that amazing framework, working with emails.

The Zend Framework’s Zend_Mail component, when coupled with the Zend Framework’s approach to minimizing redundancy and maximizing portability, offers the ideal solution for configuring and transmitting email through PHP-driven webpages. In this section, we will be using the Zend_Mail component.

First, within the application’s config.ini file, I define various parameters used to configure the transmission solution:

; email

email.smtpserver = smtp.gmail.com
email.username   = [email protected]
email.password   = strong_password
email.support    = [email protected]

Within the bootstrap.php file, I configure Zend_Mail’s transport mechanism, drawing upon the parameters defined in config.ini:

$mailConfigs = array('auth' => 'login',
'username' => $config->email->username,
'password' => $config->email->password,
'ssl' => 'tls');

$tr = new Zend_Mail_Transport_Smtp($config->email->smtpserver,
$mailConfigs);
Zend_Mail::setDefaultTransport($tr);

Although this executes with each request, the overhead required to do so is minimal and will not affect performance. Finally, I invoke code similar to the following from within the appropriate controllers:

try {
// Create a new mail object
$mail = new Zend_Mail();

$mail->setFrom($this->config->email->from_admin);
$mail->addTo("[email protected]");
$mail->setSubject("Your account has been created");

$email = "Thank you for registering!";

$mail->setBodyText($email);
$mail->send();

$this->view->success = 1;
} catch (Exception $e) {
$this->view->errors[] = "We were unable to send your
confirmation email. Please contact
{$this->config->email->support}.";
}

If you’d like to add an attachment, all you need to do is invoke the $mail object’s createAttachment() method:

$mail->createAttachment("file.pdf");

If you want to send HTML-formatted email, just use the setBodyHtml() method instead of setBodyText():

$mail->sendBodyHTML("Thank <b>you</b> for registering!");

Additional Resources

Sending email from your PHP-powered websites is easy once you’ve been provided with the necessary background, so hopefully this tutorial helped alleviate any initial confusion you had in this regard. For further information, check out the following resources for more information about sending email using PHP:

What’s Next?

In part 4 I will continue covering mail by showing you how to build a simple form to mail program in PHP. And will tell you some final notes :) So, see you in next part.

If you enjoyed this article, get email updates (it's free).

Join over 77,235 Subscribers Today.

7 Written ArticlesWebsite

Hi there! My name is Nick Plekhanov. I'm a passionate web developer and user interface designer from Russia, experienced in PHP, and MySQL along with the beautiful XHTML and CSS under jQuery stuff. I've been doing web development for 3 years. Here, I'll be your PHP coder, sometimes designer, and SEO expert. My own web development blog is coming really soon. If you’d like to connect with me, follow me on Twitter.

6 Comments Best Comments First
  • seelts

    Tuesday, November 23rd, 2010 14:47

    1

    I think it is better to use
    “filter_var($email, FILTER_VALIDATE_EMAIL);”
    to validate email addresses.

    (PHP 5.2.0+)

    0
  • Scrotta

    Tuesday, November 23rd, 2010 19:33

    2

    More useful info – http://php.net/mail

    0
  • Rahul

    Tuesday, November 23rd, 2010 19:35

    3

    Great topic as usually !!! i was reading the last 2 parts and as i said i find it always complicated and hard to deal with these languages , but i never mind to read about it to know at least the simplest things and indeed this was good to improve my knowledge so thank you for sharing it :)

    0
  • Javad Absalan

    Wednesday, November 24th, 2010 08:02

    4

    Thank u, I’m following this series of “PHP for Beginners” …
    good luck

    0
  • Ryan

    Monday, October 17th, 2011 15:36

    6

    This was a very helpful tutorial Nick. Not many people spend the time to go through things like this. Emails, SMTP servers, and sometimes formatting can be tricky, that’s why I have found it easier to leave it up to the professionals. However, now I see how things are done with your help. Keep up the great work and thanks again.

    0
  • Oliver

    Wednesday, November 24th, 2010 04:46

    5

    Mails in PHP are only fun, when you start using html mails. This method is only for simple (and boring) textmails. The tutorial is nice, but your code is really messed up by wordpress.

    0
  • Ryan

    Monday, October 17th, 2011 15:36

    6

    This was a very helpful tutorial Nick. Not many people spend the time to go through things like this. Emails, SMTP servers, and sometimes formatting can be tricky, that’s why I have found it easier to leave it up to the professionals. However, now I see how things are done with your help. Keep up the great work and thanks again.

    0
  • Oliver

    Wednesday, November 24th, 2010 04:46

    5

    Mails in PHP are only fun, when you start using html mails. This method is only for simple (and boring) textmails. The tutorial is nice, but your code is really messed up by wordpress.

    0
  • Javad Absalan

    Wednesday, November 24th, 2010 08:02

    4

    Thank u, I’m following this series of “PHP for Beginners” …
    good luck

    0
  • Rahul

    Tuesday, November 23rd, 2010 19:35

    3

    Great topic as usually !!! i was reading the last 2 parts and as i said i find it always complicated and hard to deal with these languages , but i never mind to read about it to know at least the simplest things and indeed this was good to improve my knowledge so thank you for sharing it :)

    0
  • Scrotta

    Tuesday, November 23rd, 2010 19:33

    2

    More useful info – http://php.net/mail

    0
  • seelts

    Tuesday, November 23rd, 2010 14:47

    1

    I think it is better to use
    “filter_var($email, FILTER_VALIDATE_EMAIL);”
    to validate email addresses.

    (PHP 5.2.0+)

    0

Comments are closed.

50.19.74.67 - unknown - unknown - US