Linux GitLab配置邮件服务的完整流程
若服务器未安装邮件传输代理(MTA),需先安装Postfix作为本地SMTP转发服务,避免GitLab直接连接外部SMTP服务器时因缺乏MTA而失败。
sudo apt-get update && sudo apt-get install postfix,安装过程中选择“Internet Site”,并设置系统域名(如example.com)。/etc/postfix/main.cf,添加/修改以下关键参数:myhostname = your_hostname.example.com # 服务器主机名
mydomain = example.com # 系统域名
myorigin = $mydomain # 发件域名
inet_interfaces = all # 监听所有网络接口
inet_protocols = ipv4 # 使用IPv4协议
mydestination = $myhostname, localhost.$mydomain, $mydomain # 接收邮件的域名
mynetworks = 127.0.0.0/8 [::1]/128 # 允许发送邮件的网络范围(本地+IPv6本地)
home_mailbox = Maildir/ # 邮件存储格式(Maildir)
relayhost = [smtp.yourmailprovider.com]:587 # 外部SMTP服务器地址(如Gmail)
smtp_use_tls = yes # 启用TLS加密
smtp_sasl_auth_enable = yes # 启用SMTP认证
smtp_sasl_security_options = noanonymous # 禁止匿名认证
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd # 认证信息文件路径
smtp_tls_security_level = encrypt # 强制加密传输
header_size_limit = 4096000 # 增加邮件头大小限制(避免大邮件失败)
/etc/postfix/sasl_passwd文件,添加SMTP服务器凭据(替换为实际值):[smtp.yourmailprovider.com]:587 your_email@example.com:your_password
执行sudo postmap /etc/postfix/sasl_passwd生成密码映射数据库,并设置文件权限:sudo chmod 600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
sudo systemctl restart postfix,并通过sudo systemctl status postfix确认服务状态为“active (running)”。无论是否使用Postfix,GitLab的核心邮件配置均通过/etc/gitlab/gitlab.rb文件完成(容器部署需修改持久化卷中的对应文件)。
nano或vim)打开/etc/gitlab/gitlab.rb:sudo nano /etc/gitlab/gitlab.rb
gitlab_rails['smtp_enable'] = true # 启用SMTP
gitlab_rails['smtp_address'] = "smtp.gmail.com" # SMTP服务器地址
gitlab_rails['smtp_port'] = 587 # SMTP端口(587为TLS常用端口)
gitlab_rails['smtp_user_name'] = "your_email@gmail.com" # SMTP登录用户名(需用完整邮箱)
gitlab_rails['smtp_password'] = "your_app_password" # SMTP密码(优先使用应用专用密码)
gitlab_rails['smtp_domain'] = "gmail.com" # 发件域名(与SMTP服务器匹配)
gitlab_rails['smtp_authentication'] = "login" # 认证方式(多为login或plain)
gitlab_rails['smtp_enable_starttls_auto'] = true # 自动启用STARTTLS(加密传输)
gitlab_rails['smtp_tls'] = false # 禁用SSL(与STARTTLS不冲突)
gitlab_rails['smtp_openssl_verify_mode'] = 'peer' # 验证SSL证书(生产环境建议用peer,自签名证书用none)
# 可选:设置发件人地址(需与SMTP认证用户名一致或符合服务商要求)
gitlab_rails['gitlab_email_from'] = 'gitlab@example.com'
gitlab_rails['gitlab_email_reply_to'] = 'noreply@example.com'
注意:
smtp_openssl_verify_mode设为none(不推荐生产环境使用)。Ctrl+O保存文件,Ctrl+X退出编辑器。sudo gitlab-ctl reconfigure,该命令会根据gitlab.rb的修改更新GitLab配置。sudo gitlab-ctl restart,确保所有服务(包括Rails应用)重启并加载新配置。gitlab-rails console
Notify.test_email('recipient@example.com', 'GitLab邮件测试', '这是一封来自GitLab的测试邮件').deliver_now
gitlab-rails console检查SMTP配置:# 检查ActionMailer是否启用SMTP
puts ActionMailer::Base.delivery_method # 应输出: :smtp
# 查看SMTP详细配置
puts ActionMailer::Base.smtp_settings.inspect
smtp.gmail.com:587);smtp_openssl_verify_mode设为none(仅测试环境)。/var/log/gitlab/gitlab-rails/production.log)中的错误信息;sudo systemctl status postfix);postfix check命令检查配置文件语法;/var/log/mail.log)定位具体错误。通过以上步骤,Linux环境下的GitLab即可通过SMTP服务发送通知邮件。配置完成后,用户可在GitLab的“项目设置→集成→邮件”中进一步调整通知模板和触发条件。