implement the Mailservice

This commit is contained in:
Jonas Hinterdorfer 2025-03-11 21:14:37 +01:00
parent a206678b3b
commit 0fd83b7fad
4 changed files with 78 additions and 4 deletions

View File

@ -7,4 +7,10 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,35 @@
using System.Net;
using System.Net.Mail;
namespace ConsoleApp1;
public class MailService
{
private readonly SmtpSettings _smtpSettings;
public MailService(SmtpSettings smtpSettings)
{
_smtpSettings = smtpSettings;
}
public void SendEmail(string to, string subject, string body)
{
using (var client = new SmtpClient(_smtpSettings.SmtpServer, _smtpSettings.SmtpPort))
{
client.Credentials = new NetworkCredential(_smtpSettings.SmtpUser, _smtpSettings.SmtpPassword);
client.EnableSsl = true;
var mailMessage = new MailMessage
{
From = new MailAddress(_smtpSettings.SmtpFrom),
Subject = subject,
Body = body,
IsBodyHtml = true,
};
mailMessage.To.Add(to);
client.Send(mailMessage);
}
}
}

View File

@ -1,9 +1,32 @@
namespace ConsoleApp1;
using System;
using System.IO;
using System.Text.Json;
class Program
namespace ConsoleApp1
{
static void Main(string[] args)
class Program
{
Console.WriteLine("Hello, World!");
static void Main(string[] args)
{
string jsonFilePath = "appsettings.json";
string jsonString = File.ReadAllText(jsonFilePath);
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
SmtpSettings? smtpSettings = JsonSerializer.Deserialize<SmtpSettings>(jsonString, options);
if (smtpSettings is null)
{
Console.WriteLine("Failed to deserialize SmtpSettings");
return;
}
MailService mailService = new MailService(smtpSettings);
mailService.SendEmail("user@user.com", "Hello World", "Hello World from C#!");
}
}
}

View File

@ -0,0 +1,10 @@
namespace ConsoleApp1;
public class SmtpSettings
{
public string SmtpServer { get; set; }
public int SmtpPort { get; set; }
public string SmtpUser { get; set; }
public string SmtpPassword { get; set; }
public string SmtpFrom { get; set; }
}