Wednesday, April 2, 2014

Sending emails via gmail with php

This script developed to send notifications (as well html and attachment)  to server admin through gmail account:

#!/usr/bin/php
<?php

/*

Please make sure, you have installed following pear modules:

pear install Mail
pear install Net_SMTP
pear install Mail_mime
pear install Mail_mimeDecode


IMPORTANT: Works only with utf-8 charset!!!

*/

$mailru_user = "YOUR_USER@gmail.com";
$mailru_passwd = "YOUR_PASS";
$to = '<TO_SERVER_ADMIN@gmail.com>';

require_once "Mail.php";
require_once('Mail/mime.php');

if(empty($argv[1]))exit("USAGE: $argv[0] 'Hello, how are you?' 'some text' '<h1>some html text</h1>' '/tmp/attachment.txt'");



function mail_via_gmail($subject,$text,$html,$file){
    global $mailru_user;
    $from = '<'.$mailru_user.'>';
    global $mailru_passwd;
    global $to;
    $crlf = "\r\n";
    if( empty($to) ){
        echo 'Please specify $to parameter';
        exit();
    }

    if( empty( $subject ) ) $subject = '';
    if( empty( $text ) ) $text = '';
    if( empty( $html ) ) $html = '';
    if( empty( $file ) ) $file = '';

    $headers = array(
        'From' => $from,
        'To' => $to,
        'Subject' => $subject,
        'Content-Type'  => 'text/html; charset=UTF-8'
    );


    $mime_params = array(
        'text_encoding' => '7bit',
        'text_charset'  => 'UTF-8',
        'html_charset'  => 'UTF-8',
        'head_charset'  => 'UTF-8'
    );

    $mime = new Mail_mime($crlf);

    $mime->setTXTBody($text);
    $mime->setHTMLBody($html);
    $mime->addAttachment($file,'application/octet-stream');

    $body = $mime->get($mime_params);
    $headers = $mime->headers($headers);

    $smtp = Mail::factory('smtp', array(
        'host' => 'ssl://smtp.gmail.com',
        'port' => '465',
        'auth' => true,
        'username' => $mailru_user,
        'password' => $mailru_passwd
    ));

    $mail = $smtp->send($to, $headers, $body);

    if (PEAR::isError($mail)) {
        echo('<p>' . $mail->getMessage() . '</p>');
    } else {
        echo("Message successfully sent!\n");
    }
}

@mail_via_gmail($argv[1],$argv[2],$argv[3],$argv[4]);

?>



1 comment:

  1. works with mail.ru too. Originally was made for mail.ru

    ReplyDelete