Setting up a local Ubuntu Linux machine to send email via SMTP in PHP

The following guide worked on an Ubuntu 11.04 machine.

I will assume you have an Apache2 server up and running without problems. If this is not the case, search the Ubuntu forums for LAMP.

Begin with installing the packages sendmail, php-mail and postfix:

sudo apt-get install sendmail php-mail postfix

You might get some prompts during the installation, but just follow the instructions.

Uncomment and change the sendmail_path in your file /etc/php5/apache2/php.ini. The line should now look like this:

sendmail_path = /usr/sbin/sendmail -i -t

This is needed because PHP won’t find the sendmail command otherwise.

You can either use the PHP mail() function now, or use a custom PHP library for sending emails. I recommend the latter. For a fast setup, use the Swift Mailer. Download the library, put it in your public website folder and start making scripts. Here is an example script that uses Swift:

require_once 'swift/lib/swift_required.php';

// --- Create the Transport ---
$transport = Swift_SmtpTransport::newInstance('smtp.yourdomain.com', 587)
  ->setUsername('username@yourdomain.com')
  ->setPassword('yourpassword');

// --- Create the Mailer using your created Transport ---
$mailer = Swift_Mailer::newInstance($transport);

// --- Create a message ---
$message = Swift_Message::newInstance($subject)
  ->setFrom(array('username@yourdomain.com' => 'Your Name'))
  ->setTo(array('some@email.com'))
  ->setBody('This is the message body.');

// --- Send message ---
$status = $mailer->send($message);
if($status) echo "Success!";
else echo "Failure";

Put this code into a PHP file, change the domain and SMTP server data, and run it. Hopefully, an email should be sent to the given e-mail address.

Share Button

5 thoughts on “Setting up a local Ubuntu Linux machine to send email via SMTP in PHP”

    1. I didn’t need to, I used the defaults that came when installing with apt-get. Does the config cause problems for you?

  1. i followed the steps on 2 live servers and it worked without any issue, however on an Ubuntu 16.04 machine I am not able to send mails after following the steps. where can i find the log/issue?

    thanks.

Leave a Reply

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


*