Usage
This page walks through the example from the repository: a web application publishes a "send mail" command to RabbitMQ, and a console application consumes it and sends the e-mail.
Publish a command
After registering the library, resolve ICommandSender and use its ready-made publish method:
var commandSender = (ICommandSender)httpContext.RequestServices.GetService(typeof(ICommandSender));
await commandSender.PublishSendMailCommandAsync(new SendMailCommand
{
From = "[email protected]",
FromPassword = "<smtp password>",
Port = 587,
SmtpHost = "mail.yourdomain.com",
To = "[email protected]",
Subject = "Test Mail",
HtmlBody = htmlContent
});
You can also publish commands manually instead of using ICommandSender.
Write a consumer
To receive and process the command you need a consumer project. It can be a console application, a web API or something else; this example uses a console application.
The consumer must stay up so that it keeps listening to the RabbitMQ queue and handles each new command as it arrives.
Program.cs
Build a MassTransit bus with RabbitMqBusConfigurator, attach the consumer to the mail queue and register a hosted service:
static async Task Main(string[] args)
{
Console.Title = "Milvasoft.MailSenderMicroService";
var builder = new HostBuilder().ConfigureServices((hostContext, services) =>
{
services.AddHostedService<MailHostedService>();
var busConfigurator = new RabbitMqBusConfigurator(new RabbitMqConfiguration
{
RabbitMqUri = "rabbitmq://localhost:5672/",
UserName = "<rabbitmq user>",
Password = "<rabbitmq password>",
});
var bus = busConfigurator.CreateBus(cfg =>
{
cfg.ReceiveEndpoint(RabbitMqConstants.MailServiceQueueName, e =>
{
e.Consumer<SendMailCommandConsumer>();
// Configure the receive endpoint to your needs with MassTransit.
e.UseMessageRetry(r => r.Interval(2, 30000));
e.UseRateLimit(30, TimeSpan.FromMinutes(1));
});
});
services.AddSingleton(bus);
});
await builder.RunConsoleAsync();
}
Hosted service
MailHostedService starts and stops the bus, which keeps the console application running:
using MassTransit;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Milvasoft.Consumers.Mails
{
public class MailHostedService : IHostedService
{
private readonly IBusControl _bus;
public MailHostedService(IBusControl bus)
{
_bus = bus;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await Console.Out.WriteLineAsync("Listening for Email Service commands/events...");
await _bus.StartAsync(cancellationToken).ConfigureAwait(false);
}
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Email Service stopping.");
return _bus.StopAsync(cancellationToken);
}
}
}
Consumer
SendMailCommandConsumer runs for every command that arrives in the queue it listens to:
using MassTransit;
using Milvasoft.Messaging.RabbitMq.Commands;
using System;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
namespace Milvasoft.Consumers.Mails
{
public class SendMailCommandConsumer : IConsumer<ISendMailCommand>
{
public async Task Consume(ConsumeContext<ISendMailCommand> context)
{
try
{
using var mailMessage = new MailMessage(context.Message.From,
context.Message.To,
context.Message.Subject,
context.Message.HtmlBody)
{
IsBodyHtml = true
};
using var smtpClient = new SmtpClient(context.Message.SmtpHost, context.Message.Port);
smtpClient.Credentials = new NetworkCredential(context.Message.From, context.Message.FromPassword);
await smtpClient.SendMailAsync(mailMessage).ConfigureAwait(false);
}
catch (Exception ex)
{
await Console.Out.WriteLineAsync("An error occured when sending mail.");
}
}
}
}
Queue names
RabbitMqConstants holds the queue names used by the library, including:
| Constant | Queue |
|---|---|
MailServiceQueueName | mail.service |
AuditServiceQueueName | audit.service |
NotificationServiceQueueName | notification.service |
PushServiceQueueName | push.service |
Contributing
With this setup you can run work independently of your main project over RabbitMQ. Contributions that add more operations like mail sending are welcome on GitHub.