[Git]提交后自动发email

当然是通过hooks来实现了,对应post-receive,脚本也是已经随git-core安装就有了的:/usr/share/doc/git-core/contrib/hooks/post-receive-email,不过这个脚本用到了sendmail,我想好多机器上都没配这个东东吧,好在有好心人在这个脚本的基础上进行了[完善](http://github.com/stephenh/git-central/blob/master/server/post-receive-email),可以用msmtp发信了,看来我以前[换用msmtp配mutt](379)太正确了,另外msmtp也确实比sendmail小巧多了。

首先把刚才说到的[脚本](http://github.com/stephenh/git-central/blob/master/server/post-receive-email)以及依赖文件[functions](http://github.com/stephenh/git-central/blob/master/server/functions)一起下载到某地,加上执行属性(公用),然后ln到仓库的hooks目录下:

$ cd test.git/hooks/
$ mv post-receive post-receive.origin
$ ln -s ../../gittools/post-receive-email post-receive
$ ln -s ../../gittools/functions

然后修改仓库里的config文件,注意不是客户端的:

[hooks "post-receive-email"]
    mailinglist = list1@domain.tld, list2@domain.tld
    announcelist =
    envelopesender = mailsender@domain.tld
    sendmail = /usr/bin/msmtp

其中:

  • mailinglist 默认的收信人,留空就不发信了
  • announcelist 创建tag时发送从上次创建tag以来的汇总邮件的收信人,比如用版本号作为tag的时候这就生成了每个版本的changelog,留空则用mailinglist的值
  • envelopesender 发信人/账号,要和msmtp的发信账号对应起来
  • sendmail sendmail或其它发信程序的路径

还有个环境变量$USER_EMAIL,也是个发信人,不过是显示在邮件From:里的。如果要设置邮件里的From:,需要自己修改post-receive-email或在其之前执行的脚本,设置环境变量:

export USER_EMAIL="GIT <mailsender@domain.tld>"

这一版修改中作者还去掉了原来的emailprefix设置参数,固定为用仓库里description文件的内容加上[]替代。

最后,在git(git服务器运行用户)用户的HOME下放一个.msmtprc,配置发信认证信息:

defaults
    tls_trust_file /etc/ssl/certs/ca-certificates.crt
account gmail
    host smtp.gmail.com
    port 465
    auth on
    tls on
    tls_starttls off
account mailsender@domain.tld : gmail
#   from must be same as From: in mail, exclude Name, only mail address
#   Because maybe msmtp select account using from
    from mailsender@domain.tld
    user "mailsender@domain.tld"
    password my_passwd
account default : mailsender@domain.tld

现在就可以测试push,看自动发信是否正常了。如果提示functions语法错误,比如:

hooks/functions: 213: Syntax error: Bad for loop variable

可以把这两个脚本第一行的#!/bin/sh改为#!/bin/bash

注意msmtp调用的是提交动作所属用户的.msmtprc,从本机提交和远程ssh进来可能用的就不是一个.msmtprc了。

参考

  • [Getting email from GIT](http://developer.berlios.de/docman/display_doc.php?docid=1813&group_id=2#commit-email)
  • [Setting up git commit emails](http://www.rubick.com/blogger/one-entry?entry_id=30408)
  • [help regarding for loop syntax in ubuntu 7.10](http://ubuntuforums.org/archive/index.php/t-703467.html)

2 thoughts on “[Git]提交后自动发email”

Leave a Reply

Your email address will not be published. Required fields are marked *