using System;
using System.Net.Mail;
using System.Threading.Tasks;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.HealthChecks;
using Umbraco.Core.Services;
namespace Umbraco.Web.HealthCheck.NotificationMethods
{
[HealthCheckNotificationMethod("email")]
public class EmailNotificationMethod : NotificationMethodBase, IHealthCheckNotificatationMethod
{
private readonly ILocalizedTextService _textService;
///
/// Default constructor which is used in the provider model
///
///
///
///
///
public EmailNotificationMethod(bool enabled, bool failureOnly, HealthCheckNotificationVerbosity verbosity,
string recipientEmail)
: this(enabled, failureOnly, verbosity, recipientEmail, ApplicationContext.Current.Services.TextService)
{
}
///
/// Constructor that could be used for testing
///
///
///
///
///
///
internal EmailNotificationMethod(bool enabled, bool failureOnly, HealthCheckNotificationVerbosity verbosity,
string recipientEmail, ILocalizedTextService textService)
: base(enabled, failureOnly, verbosity)
{
if (textService == null) throw new ArgumentNullException("textService");
_textService = textService;
RecipientEmail = recipientEmail;
Verbosity = verbosity;
}
public string RecipientEmail { get; private set; }
public async Task SendAsync(HealthCheckResults results)
{
if (ShouldSend(results) == false)
{
return;
}
if (string.IsNullOrEmpty(RecipientEmail))
{
return;
}
var message = _textService.Localize("healthcheck/scheduledHealthCheckEmailBody", new[]
{
DateTime.Now.ToShortDateString(),
DateTime.Now.ToShortTimeString(),
results.ResultsAsHtml(Verbosity)
});
var subject = _textService.Localize("healthcheck/scheduledHealthCheckEmailSubject");
var mailSender = new EmailSender();
using (var mailMessage = new MailMessage(UmbracoConfig.For.UmbracoSettings().Content.NotificationEmailAddress,
RecipientEmail,
string.IsNullOrEmpty(subject) ? "Umbraco Health Check Status" : subject,
message)
{
IsBodyHtml = message.IsNullOrWhiteSpace() == false
&& message.Contains("<") && message.Contains("")
})
{
await mailSender.SendAsync(mailMessage);
}
}
}
}