58 lines
2.3 KiB
C#
58 lines
2.3 KiB
C#
using System.Diagnostics.CodeAnalysis;
|
|
using System.Text.Json;
|
|
using MailKit.Net.Smtp;
|
|
using MailKit.Security;
|
|
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();
|
|
|
|
Console.WriteLine("=============== SMTP CONFIG LOADED ==============");
|
|
Console.WriteLine($"Config full path: {Path.GetFullPath(MailerConfig.DefaultFile)}");
|
|
Console.WriteLine($"SMTP host: {config!.SmtpServerUrl}");
|
|
Console.WriteLine($"SMTP port: {config.SmtpPort}");
|
|
Console.WriteLine($"SMTP username: {config.SmtpUsername}");
|
|
Console.WriteLine($"Sender: {config.SenderName} <{config.SenderAddress}>");
|
|
Console.WriteLine("==================================================");
|
|
|
|
|
|
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("plain") { Text = body }
|
|
};
|
|
|
|
using var smtp = new SmtpClient();
|
|
|
|
try
|
|
{
|
|
await smtp.ConnectAsync(config.SmtpServerUrl, config.SmtpPort, SecureSocketOptions.StartTls);
|
|
await smtp.AuthenticateAsync(config.SmtpUsername, config.SmtpPassword);
|
|
await smtp.SendAsync(msg);
|
|
await smtp.DisconnectAsync(true);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine(ex.ToString());
|
|
throw; // keep while testing
|
|
}
|
|
}
|
|
|
|
[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);
|
|
}
|
|
} |