Send email with PHP using an external SMTP account

PEAR modules

To make sure your emails are delivered properly, configure your PHP script or PHP application to use an external SMTP account. The following example shows how to do this using a Gmail account.

  • Install the Mail and Net_SMTP PEAR modules:

    $ sudo /opt/bitnami/php/bin/pear install pear/Net_SMTP pear/Mail-1.4.1

    Note that if these packages are already installed in your system you see the messages below when executing that command:

    Ignoring installed package pear/Net_SMTP
    Ignoring installed package pear/Mail
    Nothing to install
  • Use the script below to send an email. Place it in your pear directory and execute it with the PHP CLI:

    require_once "Mail.php";
    $from = "";
    $to = '';
    $host = "ssl://";
    $port = "465";
    $username = '';
    $password = 'mypassword';
    $subject = "test";
    $body = "test";
    $headers = array ('From' => $from, 'To' => $to,'Subject' => $subject);
    $smtp = Mail::factory('smtp',
      array ('host' => $host,
        'port' => $port,
        'auth' => true,
        'username' => $username,
        'password' => $password));
    $mail = $smtp->send($to, $headers, $body);
    if (PEAR::isError($mail)) {
    } else {
      echo("Message successfully sent!\n");


To use sendmail instead of an external SMTP server, first check that sendmail is installed by executing the command below:

$ sudo /usr/sbin/sendmail -q

If sendmail is not installed, install it with the command below:

  • Debian:

    $ sudo apt-get install sendmail
  • CentOS:

    $ sudo yum install sendmail

Configure PHP to use sendmail by uncommenting this line in the PHP configuration file at /opt/bitnami/php/etc/php.ini:

sendmail_path = "env -i /usr/sbin/sendmail -t -i"
Last modification April 8, 2020