email.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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: NewNotifierBase(model.Name, model.Type, model.Settings),
  26. Addresses: strings.Split(addressesString, "\n"),
  27. log: log.New("alerting.notifier.email"),
  28. }, nil
  29. }
  30. func (this *EmailNotifier) Notify(context *alerting.EvalContext) {
  31. this.log.Info("Sending alert notification to", "addresses", this.Addresses)
  32. metrics.M_Alerting_Notification_Sent_Email.Inc(1)
  33. ruleUrl, err := context.GetRuleUrl()
  34. if err != nil {
  35. this.log.Error("Failed get rule link", "error", err)
  36. return
  37. }
  38. cmd := &m.SendEmailCommand{
  39. Data: map[string]interface{}{
  40. "Title": context.GetNotificationTitle(),
  41. "State": context.Rule.State,
  42. "Name": context.Rule.Name,
  43. "StateModel": context.GetStateModel(),
  44. "Message": context.Rule.Message,
  45. "RuleUrl": ruleUrl,
  46. "ImageLink": context.ImagePublicUrl,
  47. "AlertPageUrl": setting.AppUrl + "alerting",
  48. "EvalMatches": context.EvalMatches,
  49. },
  50. To: this.Addresses,
  51. Template: "alert_notification.html",
  52. }
  53. if err := bus.Dispatch(cmd); err != nil {
  54. this.log.Error("Failed to send alert notification email", "error", err)
  55. }
  56. }