Innovenergy_trunk/csharp/Lib/Mailer/Mailer.cs

41 lines
1.6 KiB
C#

using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using MailKit.Net.Smtp;
using MimeKit;
namespace InnovEnergy.Lib.Mailer;
public static class Mailer
{
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "<Pending>")]
public static async Task Send(String recipientName, String recipientEmailAddress, String subject, String body)
{
var config = await ReadMailerConfig();
var from = new MailboxAddress(config!.SenderName, config.SenderAddress);
var to = new MailboxAddress(recipientName, recipientEmailAddress);
var msg = new MimeMessage
{
From = { from },
To = { to },
Subject = subject,
Body = new TextPart { Text = body }
};
using var smtp = new SmtpClient();
await smtp.ConnectAsync(config.SmtpServerUrl, config.SmtpPort, false);
await smtp.AuthenticateAsync(config.SmtpUsername, config.SmtpPassword);
await smtp.SendAsync(msg);
await smtp.DisconnectAsync(true);
}
[RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.DeserializeAsync<TValue>(Stream, JsonSerializerOptions, CancellationToken)")]
private static async Task<MailerConfig?> ReadMailerConfig()
{
await using var fileStream = File.OpenRead(MailerConfig.DefaultFile);
return await JsonSerializer.DeserializeAsync<MailerConfig>(fileStream);
}
}