Innovenergy_trunk/csharp/Lib/Mailer/Mailer.cs

41 lines
1.6 KiB
C#
Raw Normal View History

2023-10-26 12:09:38 +00:00
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using MailKit.Net.Smtp;
using MimeKit;
namespace InnovEnergy.Lib.Mailer;
2023-10-26 12:09:38 +00:00
public static class Mailer
{
2023-10-26 12:09:38 +00:00
[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)
{
2023-10-26 12:09:38 +00:00
var config = await ReadMailerConfig();
var from = new MailboxAddress(config!.SenderName, config.SenderAddress);
var to = new MailboxAddress(recipientName, recipientEmailAddress);
var msg = new MimeMessage
{
2023-10-26 12:09:38 +00:00
From = { from },
To = { to },
Subject = subject,
Body = new TextPart { Text = body }
};
2023-10-26 12:09:38 +00:00
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);
}
2023-10-26 12:09:38 +00:00
[RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.DeserializeAsync<TValue>(Stream, JsonSerializerOptions, CancellationToken)")]
private static async Task<MailerConfig?> ReadMailerConfig()
{
2023-10-26 12:09:38 +00:00
await using var fileStream = File.OpenRead(MailerConfig.DefaultFile);
return await JsonSerializer.DeserializeAsync<MailerConfig>(fileStream);
}
}