email.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. )
  10. func init() {
  11. alerting.RegisterNotifier("email", NewEmailNotifier)
  12. }
  13. type EmailNotifier struct {
  14. NotifierBase
  15. Addresses []string
  16. log log.Logger
  17. }
  18. func NewEmailNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  19. addressesString := model.Settings.Get("addresses").MustString()
  20. if addressesString == "" {
  21. return nil, alerting.ValidationError{Reason: "Could not find addresses in settings"}
  22. }
  23. return &EmailNotifier{
  24. NotifierBase: NotifierBase{
  25. Name: model.Name,
  26. Type: model.Type,
  27. },
  28. Addresses: strings.Split(addressesString, "\n"),
  29. log: log.New("alerting.notifier.email"),
  30. }, nil
  31. }
  32. func (this *EmailNotifier) Notify(context *alerting.EvalContext) {
  33. this.log.Info("Sending alert notification to", "addresses", this.Addresses)
  34. metrics.M_Alerting_Notification_Sent_Email.Inc(1)
  35. ruleUrl, err := context.GetRuleUrl()
  36. if err != nil {
  37. this.log.Error("Failed get rule link", "error", err)
  38. return
  39. }
  40. cmd := &m.SendEmailCommand{
  41. Data: map[string]interface{}{
  42. "Title": context.GetNotificationTitle(),
  43. "RuleState": context.Rule.State,
  44. "RuleName": context.Rule.Name,
  45. "Severity": context.Rule.Severity,
  46. "RuleUrl": ruleUrl,
  47. },
  48. To: this.Addresses,
  49. Template: "alert_notification.html",
  50. }
  51. if err := bus.Dispatch(cmd); err != nil {
  52. this.log.Error("Failed to send alert notification email", "error", err)
  53. }
  54. }