googlelimesurvey

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
    
  • Restart PHP-FPM:

      $ sudo /opt/bitnami/ctlscript.sh restart php-fpm
    
  • Use the script below to send an email. Place it in your pear directory and execute it with the PHP CLI:

      <?php
      require_once "Mail.php";
    
      $from = "myaccount@gmail.com";
      $to = 'test@mytest.com';
    
      $host = "ssl://smtp.gmail.com";
      $port = "465";
      $username = 'myaccount@gmail.com';
      $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)) {
        echo($mail->getMessage());
      } else {
        echo("Message successfully sent!\n");
      }
      ?>
    

Sendmail

To use sendmail instead of an external SMTP server, follow these steps:

  • 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:

          $ sudo apt-get 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"
    
  • Restart PHP-FPM:

      $ sudo /opt/bitnami/ctlscript.sh restart php-fpm
    
Last modification December 21, 2022