Sending git notifications via Gmail SMTP server

Hosting SMTP server like sendmail/postfix by yourself is a bit high cost and emails easily go to spam folder if you don’t setup DNS stuff. Instead, let’s use Gmail SMTP server to send notification emails from git.

You need to edit post-receive-email a bit.

send_mail()
{
#       if [ -n "$envelopesender" ]; then
#               /usr/sbin/sendmail -t -f "$envelopesender"
#       else
#               /usr/sbin/sendmail -t
#       fi
        /path/to/bin/sendmail.php
}

This file supposed to be on your remote server.
% /usr/local/git/whatever-your-repository-path/hooks/post-receive

Here is sendmail.php:

#!/usr/bin/php -d include_path=/usr/share/pear
<?php
//  % pear install Mail_mimeDecode
require_once "Mail.php";
require_once "Mail/mimeDecode.php";
 
$from = "Agent Smith <your-gmail-address@gmail.com>";
$to   = "Developers <it-might-be-your-mailing-list@example.com>";
 
$original = file_get_contents('php://stdin'); // will receive data via hooks/post-receive
$decoder = new Mail_mimeDecode($original);
$mail = $decoder->decode(array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => true));
 
$host = "tls://smtp.gmail.com";
$port = 465;
$username = "your-gmail-address@gmail.com";// Google Apps also works
$password = "***your password***";
 
$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $mail->headers['subject']);
$smtp = Mail::factory('smtp',
    array ('host' => $host,
    'port' => $port,
    'auth' => true,
    'username' => $username,
    'password' => $password));
 
$mail = $smtp->send($to, $headers, $mail->body);
 
if (PEAR::isError($mail)) {
    echo $mail->getMessage(), PHP_EOL;
} else {
    echo 'Message successfully sent!', PHP_EOL;
}

That’s it. You will receive emails via Gmail SMTP server when someone does ‘git push’. It should work on CentOS 5.3 + PHP5.2.10 + git 1.6.4.4.

This entry was posted in Tweak. Bookmark the permalink. Trackbacks are closed, but you can post a comment.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">