Tuesday 25 June 2013

Using PHP to send emails on a Ubuntu Server

This is a rather basic way of quickly getting PHP to send an email when running on a Ubuntu server. A couple of prerequisites must be fulfilled first.

For this example we are going to use sendmail with added libraries for SMTP over TLS. (a requirement for using Google Mail) To ensure we have the packages we need to run the following:

 $ sudo apt-get install sendmail  
 $ sudo apt-get install libio-socket-ssl-perl libnet-ssleay-perl  

To test that this is working, use an existing Gmail account that you have access to and type the following in:
 sendemail -f from@email.com -t to@email.com -u Testing -m "This is a test"-s smtp.gmail.com:587 -o tls=yes -xu from@email.com -xp  

Put in the email you are sending from after -f, who you are sending to after -t and provide your gmail username after -xu. After you hit enter it will ask you for the password, this is better than having your password in-line for that command as it will then be on your command-line history.

If all goes well you will get:
 Jun 25 14:35:37 server-name sendemail[10667]: Email was sent successfully!  

Next we are going to take advantage of the PEAR framework to get the Mail module for our PHP code. Check that you have PEAR by:
 $ pear version
PEAR Version: 1.9.4
PHP Version: 5.3.10-1ubuntu3.6

If not installed you can quickly do this by running:
 $ sudo apt-get install php-pear  

We need the module Mail.php for this example, using the PEAR framework to get this is as simple as running:
 $ sudo pear install Mail  

Now we can setup our page and PHP code. This will be a basic HTML form that attempts to send an email when the submit button is pressed.

The PHP code:
 <?php  
     require_once 'Mail.php';  
     $recipients = "to@email.com";  
     $headers["From"] = "from@email.com";  
     $headers["To"] = "to@email.com";  
     $headers["Subject"] = "Expression of Interest";  
     $msg = "Hi, ".$_POST['email']." is interested in our product!";  
     $smtpinfo["host"] = "smtp.gmail.com";  
     $smtpinfo["port"] = "587";  
     $smtpinfo["auth"] = true;  
     $smtpinfo["username"] = "from@email.com";  
     $smtpinfo["password"] = "password";  
     if($_POST['send_email']) {  
         $mail_object =& Mail::factory("smtp", $smtpinfo);  
         $mail_object->send($recipients, $headers, $msg);  
     }  
 ?>  


The HTML code:
 <form action="" method="POST" id="contactFormHeader">  
    <input type="hidden" name="send_email" id="send_email">  
    <label for="name">Name</label>  
    <input type="text" name="name" id="name" class="required" />  
    <label for="email">E-mail</label>  
    <input type="text" name="email" id="email" class="required email" />  
    <button type="submit" name="submit" id="submit">Submit</button>  
 </form>  

There you go, a basic PHP driven HTML contact form that sends an email via SMTP over TLS by way of your Gmail account.


No comments:

Post a Comment