Mail Module
Allows you to send mails. Contains a helper to render razor pages for a html body.
Configuration
In order for the Mail Module to work the mail server must be configured. The following default configuration expects a mail server running locally without authentication.
{
"ConfinityMail" : {
"Server": "localhost",
"Port": 25,
"Username": null,
"Password": null,
"EnableSsl": false,
"FromEmailAddress": null
}
}
Linux: In order for e-mail authentication to work, the package gss-ntlmssp must be installed.
Usage Send Mail
Inject IMailService an call the SendAsync method.
Simple example:
_mailService.SendAsync(message => message.To("root@localhost")
.From("noreply@localhost")
.Subject("hello world")
.TextBody("this is the body \n bye"));
Example with razor view:
See Render Razor View for an explanations.
public class MailLaunchExample : IBackendActionSingle<ConfinityRowSelection, BackendActionSimpleResult>
{
private readonly IMailService _mailService;
private readonly IConfinityDbContext _dbContext;
private readonly IRazorToStringRenderer _renderer;
public MailLaunchExample(IMailService mailService, IConfinityDbContext dbContext,
IRazorToStringRenderer renderer)
{
_mailService = mailService;
_dbContext = dbContext;
_renderer = renderer;
}
public async Task<BackendActionSimpleResult> Execute(ConfinityRowSelection selectedAsset)
{
var launch = _dbContext.Set<Launch>().Single(a => a.Id == selectedAsset.Id);
string subject = "Launch " + launch.Name;
string body = $"The launch is expected to be executed between {launch.WindowStart} and {launch.WindowEnd}";
try
{
var htmlBody =
await _renderer.RenderToStringAsync(MailModule.TitleTextMailView,
new TitleTextMailModel(subject, body));
await _mailService.SendAsync(message => message.To("rim@conx.ch")
.From("noreply@conx.ch")
.Subject(subject)
// .AlternateTextBody(body)
.HtmlBody(htmlBody));
}
catch (Exception e)
{
return new FailedSimpleBackendActionResult("unable to send mail: " + e.Message);
}
return new SuccessfulSimpleBackendActionResult("mail sent");
}
}
Render Razor view
To render a Razor view as body, you have to render it to a string. Our helper for this is IRazorViewToStringRenderer.
- In
_ViewStartspecify your layout:
@{
Layout = "ConfinityMail/DefaultMailTemplate";
}
- Create your view
- Call the method
RenderViewToStringAsyncfromIRazorViewToStringRendererand pass in your view and your model.
Current Limitations
- fire and forget - when the mail server is offline no resend is made.