implement the Mailservice
This commit is contained in:
parent
a206678b3b
commit
0fd83b7fad
@ -7,4 +7,10 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appsettings.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
35
ConsoleApp1/MailService.cs
Normal file
35
ConsoleApp1/MailService.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,9 +1,32 @@
|
||||
namespace ConsoleApp1;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
class Program
|
||||
namespace ConsoleApp1
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Console.WriteLine("Hello, World!");
|
||||
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#!");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
10
ConsoleApp1/SmtpSettings.cs
Normal file
10
ConsoleApp1/SmtpSettings.cs
Normal 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; }
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user