Skip to content

Commit

Permalink
Update to use IEmailSender when contributors are deleted
Browse files Browse the repository at this point in the history
  • Loading branch information
ardalis committed Mar 4, 2024
1 parent d87414d commit 83cef4b
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 14 deletions.
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageVersion Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.1" />
<PackageVersion Include="NSubstitute" Version="5.1.0" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Clean.Architecture.Core.ContributorAggregate.Events;
using Clean.Architecture.Core.Interfaces;
using MediatR;
using Microsoft.Extensions.Logging;

Expand All @@ -7,13 +8,16 @@ namespace Clean.Architecture.Core.ContributorAggregate.Handlers;
/// <summary>
/// NOTE: Internal because ContributorDeleted is also marked as internal.
/// </summary>
internal class ContributorDeletedHandler(ILogger<ContributorDeletedHandler> _logger) : INotificationHandler<ContributorDeletedEvent>
internal class ContributorDeletedHandler(ILogger<ContributorDeletedHandler> logger,
IEmailSender emailSender) : INotificationHandler<ContributorDeletedEvent>
{
public async Task Handle(ContributorDeletedEvent domainEvent, CancellationToken cancellationToken)
{
_logger.LogInformation("Handling Contributed Deleted event for {contributorId}", domainEvent.ContributorId);
logger.LogInformation("Handling Contributed Deleted event for {contributorId}", domainEvent.ContributorId);

// TODO: do meaningful work here
await Task.Delay(1);
await emailSender.SendEmailAsync("[email protected]",
"[email protected]",
"Contributor Deleted",
$"Contributor with id {domainEvent.ContributorId} was deleted.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" />
<PackageReference Include="Microsoft.Extensions.Configuration" />
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
<PackageReference Include="SQLite" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Clean.Architecture.Infrastructure.Email;

public class MailserverConfiguration()
{
public string Hostname { get; set; } = "localhost";
public int Port { get; set; } = 25;
}
22 changes: 17 additions & 5 deletions src/Clean.Architecture.Infrastructure/Email/MimeKitEmailSender.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,38 @@
using Clean.Architecture.Core.Interfaces;
using MailKit.Net.Smtp;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;

namespace Clean.Architecture.Infrastructure.Email;

public class MimeKitEmailSender(ILogger<MimeKitEmailSender> _logger) : IEmailSender
public class MimeKitEmailSender : IEmailSender
{
private readonly ILogger<MimeKitEmailSender> _logger;
private readonly MailserverConfiguration _mailserverConfiguration;

public MimeKitEmailSender(ILogger<MimeKitEmailSender> logger,
IOptions<MailserverConfiguration> mailserverOptions)
{
_logger = logger;
_mailserverConfiguration = mailserverOptions.Value!;

}


public async Task SendEmailAsync(string to, string from, string subject, string body)
{
_logger.LogInformation("Attempting to send email to {to} from {from} with subject {subject}...", to, from, subject);
_logger.LogWarning("Sending email to {to} from {from} with subject {subject} using {type}.", to, from, subject, this.ToString());

using var client = new SmtpClient(); // use localhost and a test server
client.Connect("localhost", 25, false); // TODO: pull settings from config
using var client = new SmtpClient();
client.Connect(_mailserverConfiguration.Hostname, _mailserverConfiguration.Port, false);
var message = new MimeMessage();
message.From.Add(new MailboxAddress(from, from));
message.To.Add(new MailboxAddress(to, to));
message.Subject = subject;
message.Body = new TextPart("plain") { Text = body };

await client.SendAsync(message);
_logger.LogInformation("Email sent!");

client.Disconnect(true);
}
Expand Down
22 changes: 19 additions & 3 deletions src/Clean.Architecture.Infrastructure/Email/SmtpEmailSender.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
using System.Net.Mail;
using Clean.Architecture.Core.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Clean.Architecture.Infrastructure.Email;

public class SmtpEmailSender(ILogger<SmtpEmailSender> _logger) : IEmailSender
/// <summary>
/// MimeKit is recommended over this now:
/// https://weblogs.asp.net/sreejukg/system-net-mail-smtpclient-is-not-recommended-anymore-what-is-the-alternative
/// </summary>
public class SmtpEmailSender : IEmailSender
{
private readonly MailserverConfiguration _mailserverConfiguration;
private readonly ILogger<SmtpEmailSender> _logger;

public SmtpEmailSender(ILogger<SmtpEmailSender> logger,
IOptions<MailserverConfiguration> mailserverOptions)
{
_mailserverConfiguration = mailserverOptions.Value!;
_logger = logger;
}

public async Task SendEmailAsync(string to, string from, string subject, string body)
{
var emailClient = new SmtpClient("localhost"); // TODO: pull settings from config
var emailClient = new SmtpClient(_mailserverConfiguration.Hostname, _mailserverConfiguration.Port);

var message = new MailMessage
{
From = new MailAddress(from),
Expand All @@ -17,6 +33,6 @@ public async Task SendEmailAsync(string to, string from, string subject, string
};
message.To.Add(new MailAddress(to));
await emailClient.SendMailAsync(message);
_logger.LogWarning("Sending email to {to} from {from} with subject {subject}.", to, from, subject);
_logger.LogWarning("Sending email to {to} from {from} with subject {subject} using {type}.", to, from, subject, this.ToString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Clean.Architecture.Core.Services;
using Clean.Architecture.Infrastructure.Data;
using Clean.Architecture.Infrastructure.Data.Queries;
using Clean.Architecture.Infrastructure.Email;
using Clean.Architecture.UseCases.Contributors.List;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
Expand All @@ -29,6 +30,8 @@ public static IServiceCollection AddInfrastructureServices(
services.AddScoped<IListContributorsQueryService, ListContributorsQueryService>();
services.AddScoped<IDeleteContributorService, DeleteContributorService>();

services.Configure<MailserverConfiguration>(config.GetSection("Mailserver"));

logger.LogInformation("{Project} services registered", "Infrastructure");

return services;
Expand Down
9 changes: 7 additions & 2 deletions src/Clean.Architecture.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,17 @@

if (builder.Environment.IsDevelopment())
{
builder.Services.AddScoped<IEmailSender, FakeEmailSender>();
// Use a local test email server
// See: https://ardalis.com/configuring-a-local-test-email-server/
builder.Services.AddScoped<IEmailSender, MimeKitEmailSender>();

// Otherwise use this:
//builder.Services.AddScoped<IEmailSender, FakeEmailSender>();
AddShowAllServicesSupport();
}
else
{
builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();
builder.Services.AddScoped<IEmailSender, MimeKitEmailSender>();
}

var app = builder.Build();
Expand Down
4 changes: 4 additions & 0 deletions src/Clean.Architecture.Web/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,9 @@
// }
//}
]
},
"Mailserver": {
"Server": "localhost",
"Port": 25
}
}

0 comments on commit 83cef4b

Please sign in to comment.