email.go 2.0 KB

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