Sep 11, 2012

Sending e-mail via PHP and MSMTP

Normally I would have set up a fully-fledged mailing systems like Postfix or Sendmail to handle my mailing needs. This means spending hours configuring, tweaking and securing another service running on my server. But I have found a simpler way.

MSMTP.

  1. Install MSMTP. In Ubuntu you would do the following:

    sudo apt-get install msmtp ca-certificates
  2. Edit the configuration file /etc/msmtprc with the following:

    #set defaults
    defaults

    # Enable or disable TLS/SSL encryption
    tls off
    tls_starttls on
    tls_trust_file /etc/ssl/certs/ca-certificates.crt

    # account settings
    account default
    host mail.optusnet.com.au # CHANGE THIS!!!
    port 25
    auth off
    from do-not-reply@domain.com.au
    logfile /var/log/msmtp/msmtp.log
  3. Edit the configuration of PHP to use MSMTP. Edit the configuration file with the following (in Ubuntu and PHP5, the file is stored in /etc/php5/cli/php.ini

    sendmail_path = /usr/bin/msmtp -t
  4. Create the log file directory and set proper permissions (depends on how your machine is set up:

    sudo mkdir /var/log/msmtp
    sudo chown [user]:[group] /var/log/msmtp
  5. Tell our system to rotate the logs so that they do not get too large by creating the file /etc/logrotate.d/msmtp:
    /var/log/msmtp/*.log {
    rotate 12
    monthly
    compress
    missingok
    notifempty

    }
  6. You can now test it with the following PHP script:

    <?php
    $to = "your-email@domain.com";
    $subject = "Test mail";
    $message = "Hello! This is a simple email message.";
    if (mail($to,$subject,$message)) {
        echo "Mail Sent.";
    } else {
        echo "NOT SENT.";
    }

References:

1 comment:

  1. Note that in Ubuntu the Apache and CLI have different PHP5 configurations.

    This was a MASSIVE source of head-aches for a few hours!!

    ReplyDelete

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!