email.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package notifiers
  2. import (
  3. "strings"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/log"
  6. "github.com/grafana/grafana/pkg/metrics"
  7. m "github.com/grafana/grafana/pkg/models"
  8. "github.com/grafana/grafana/pkg/services/alerting"
  9. "github.com/grafana/grafana/pkg/setting"
  10. )
  11. func init() {
  12. alerting.RegisterNotifier("email", NewEmailNotifier)
  13. }
  14. type EmailNotifier struct {
  15. NotifierBase
  16. Addresses []string
  17. log log.Logger
  18. }
  19. func NewEmailNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  20. addressesString := model.Settings.Get("addresses").MustString()
  21. if addressesString == "" {
  22. return nil, alerting.ValidationError{Reason: "Could not find addresses in settings"}
  23. }
  24. return &EmailNotifier{
  25. NotifierBase: NotifierBase{
  26. Name: model.Name,
  27. Type: model.Type,
  28. },
  29. Addresses: strings.Split(addressesString, "\n"),
  30. log: log.New("alerting.notifier.email"),
  31. }, nil
  32. }
  33. func (this *EmailNotifier) Notify(context *alerting.EvalContext) {
  34. this.log.Info("Sending alert notification to", "addresses", this.Addresses)
  35. metrics.M_Alerting_Notification_Sent_Email.Inc(1)
  36. ruleUrl, err := context.GetRuleUrl()
  37. if err != nil {
  38. this.log.Error("Failed get rule link", "error", err)
  39. return
  40. }
  41. cmd := &m.SendEmailCommand{
  42. Data: map[string]interface{}{
  43. "Title": context.GetNotificationTitle(),
  44. "State": context.Rule.State,
  45. "Name": context.Rule.Name,
  46. "Severity": context.Rule.Severity,
  47. "SeverityColor": context.GetColor(),
  48. "Message": context.Rule.Message,
  49. "RuleUrl": ruleUrl,
  50. "ImageLink": context.ImagePublicUrl,
  51. "AlertPageUrl": setting.AppUrl + "alerting",
  52. "EvalMatches": context.EvalMatches,
  53. },
  54. To: this.Addresses,
  55. Template: "alert_notification.html",
  56. }
  57. if err := bus.Dispatch(cmd); err != nil {
  58. this.log.Error("Failed to send alert notification email", "error", err)
  59. }
  60. }