From 9b1293e40703e9568fa150c95d928e3c2627432c Mon Sep 17 00:00:00 2001 From: Julius Volz Date: Thu, 15 Aug 2013 09:05:12 +0200 Subject: [PATCH] Implement smarthost-based email notifications. Change-Id: Ib7dbd70ca96783f87cd44af0d7338aad754e4c72 --- manager/notifier.go | 48 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/manager/notifier.go b/manager/notifier.go index 796b0507..67761674 100644 --- a/manager/notifier.go +++ b/manager/notifier.go @@ -21,16 +21,34 @@ import ( "io/ioutil" "log" "net/http" + "net/smtp" "sync" + "text/template" pb "github.com/prometheus/alertmanager/config/generated" ) const contentTypeJson = "application/json" +const bodyTmpl = `Subject: [ALERT] {{.Labels.alertname}}: {{.Summary}} + +{{.Description}} + +Grouping labels: +{{range $label, $value := .Labels}} + {{$label}} = "{{$value}}" +{{end}} + +Payload labels: +{{range $label, $value := .Payload}} + {{$label}} = "{{$value}}" +{{end}}` + var ( notificationBufferSize = flag.Int("notificationBufferSize", 1000, "Size of buffer for pending notifications.") pagerdutyApiUrl = flag.String("pagerdutyApiUrl", "https://events.pagerduty.com/generic/2010-04-15/create_event.json", "PagerDuty API URL.") + smtpSmartHost = flag.String("smtpSmartHost", "", "Address of the smarthost to send all email notifications to.") + smtpSender = flag.String("smtpSender", "alertmanager@example.org", "Sender email address to use in email notifications.") ) // A Notifier is responsible for sending notifications for events according to @@ -140,8 +158,31 @@ func (n *notifier) sendPagerDutyNotification(serviceKey string, event *Event) er } func (n *notifier) sendEmailNotification(email string, event *Event) error { - // BUG: Implement email notifications. - log.Printf("Would send email notification for event %s to %s\n", event, email) + // Connect to the SMTP smarthost. + c, err := smtp.Dial(*smtpSmartHost) + if err != nil { + return err + } + defer c.Quit() + + // Set the sender and recipient. + c.Mail(*smtpSender) + c.Rcpt(email) + + // Send the email body. + wc, err := c.Data() + if err != nil { + return err + } + defer wc.Close() + + t := template.New("message") + if _, err := t.Parse(bodyTmpl); err != nil { + return err + } + if err := t.Execute(wc, event); err != nil { + return err + } return nil } @@ -156,6 +197,9 @@ func (n *notifier) handleNotification(event *Event, config *pb.NotificationConfi } } for _, emailConfig := range config.EmailConfig { + if *smtpSmartHost == "" { + log.Printf("No SMTP smarthost configured, not sending email notification.") + } if err := n.sendEmailNotification(emailConfig.GetEmail(), event); err != nil { log.Printf("Error sending email notification: %s", err) }