PHP Send Email via Google SMTP Server

To use the following script, you need:
1. Install PEAR Mail (See: Install PHP PEAR)
2. Add php_openssl.dll extension in php.ini
3. A google account

Function:
require_once( 'Mail.php' );

// Before use:
// 1. Add a php extension in php.ini: php_openssl.dll
// 2. Set $smtpUsername and $smtpPassword (Use a google account)
function sendmail( $from, $to, $subject, $body ) {
    $smtpHost = 'ssl://smtp.gmail.com';
    $smtpPort = '465';
    $smtpUsername = 'example@gmail.com';
    $smtpPassword = 'password';
    $headers = array(
        'From' => $from,
        'To' => $to,
        'Subject' => $subject
    );
    $smtp = @Mail::factory('smtp', array(
            'host' => $smtpHost,
            'port' => $smtpPort,
            'auth' => true,
            'username' => $smtpUsername,
            'password' => $smtpPassword
        ));
    $mail = @$smtp->send($to, $headers, $body);

    if ( @PEAR::isError($mail) ) {
        return false;
    } else {
        return true;
    }
}

Usage:
$from = 'from@gmail.com';
$to = 'to@gmail.com';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";
var_dump( sendmail( $from, $to, $subject, $body ) );

No comments:

Post a Comment