Switched from internal smtp client to MailKit. Added ssl config and improved mail service

This commit is contained in:
Marcel Baumgartner
2023-04-21 18:20:15 +02:00
parent f41dbe07f8
commit 9d4487396b
3 changed files with 28 additions and 14 deletions

View File

@@ -1,9 +1,11 @@
using System.Net;
using System.Net.Mail;
using Logging.Net;
using MimeKit;
using Moonlight.App.Database.Entities;
using Moonlight.App.Exceptions;
using Moonlight.App.Helpers;
using SmtpClient = MailKit.Net.Smtp.SmtpClient;
namespace Moonlight.App.Services;
@@ -13,6 +15,7 @@ public class MailService
private readonly string Password;
private readonly string Email;
private readonly int Port;
private readonly bool Ssl;
public MailService(ConfigService configService)
{
@@ -24,6 +27,7 @@ public class MailService
Password = mailConfig.GetValue<string>("Password");
Email = mailConfig.GetValue<string>("Email");
Port = mailConfig.GetValue<int>("Port");
Ssl = mailConfig.GetValue<bool>("Ssl");
}
public async Task SendMail(
@@ -54,20 +58,24 @@ public class MailService
{
using var client = new SmtpClient();
client.Host = Server;
client.Port = Port;
client.EnableSsl = true;
client.Credentials = new NetworkCredential(Email, Password);
await client.SendMailAsync(new MailMessage()
var mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(Email, Email));
mailMessage.To.Add(new MailboxAddress(user.Email, user.Email));
mailMessage.Subject = $"Hey {user.FirstName}, there are news from moonlight";
var body = new BodyBuilder
{
From = new MailAddress(Email),
Sender = new MailAddress(Email),
Body = parsed,
IsBodyHtml = true,
Subject = $"Hey {user.FirstName}, there are news from moonlight",
To = { new MailAddress(user.Email) }
});
HtmlBody = parsed
};
mailMessage.Body = body.ToMessageBody();
using (var smtpClient = new SmtpClient())
{
await smtpClient.ConnectAsync(Server, Port, Ssl);
await smtpClient.AuthenticateAsync(Email, Password);
await smtpClient.SendAsync(mailMessage);
await smtpClient.DisconnectAsync(true);
}
}
catch (Exception e)
{

View File

@@ -24,6 +24,7 @@
<PackageReference Include="GravatarSharp.Core" Version="1.0.1.2" />
<PackageReference Include="JWT" Version="10.0.2" />
<PackageReference Include="Logging.Net" Version="1.1.0" />
<PackageReference Include="MailKit" Version="4.0.0" />
<PackageReference Include="Mappy.Net" Version="1.0.2" />
<PackageReference Include="Markdig" Version="0.31.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.3">

View File

@@ -57,7 +57,8 @@
"Email": "no-reply@mycoolproject.de",
"Server": "mycoolproject.de",
"Password": "s3cr3t",
"Port": 25
"Port": 465,
"Ssl": true
},
"Cleanup": {
"Cpu": 90,
@@ -73,6 +74,10 @@
"Enable": false,
"Url": ""
}
},
"DiscordNotifications": {
"Enable": false,
"WebHook": ""
}
}
}