SmtpSender added

This commit is contained in:
2021-02-04 21:26:26 +01:00
parent a42bfb8c6d
commit 745b6d22a9
6 changed files with 88 additions and 10 deletions

View File

@@ -1,8 +0,0 @@
using System;
namespace Massmailer.Shared
{
public class Class1
{
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Massmailer.Shared
{
public interface IMailer
{
Task SendMailAsync(string email, string subject, string body);
}
}

View File

@@ -0,0 +1,44 @@
using MailKit.Net.Smtp;
using Massmailer.Shared.Model;
using MimeKit;
using System;
using System.Threading.Tasks;
namespace Massmailer.Shared.Logic
{
public class Mailer : IMailer
{
private readonly SmtpSettings smtpSettings;
public Mailer(SmtpSettings smtpSettings)
{
this.smtpSettings = smtpSettings;
}
public async Task SendMailAsync(string email, string subject, string body)
{
try
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(this.smtpSettings.SenderName, this.smtpSettings.SenderEmail));
message.To.Add(new MailboxAddress(email, email));
message.Subject = subject;
message.Body = new TextPart("html") { Text = body };
using (var client = new SmtpClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
await client.ConnectAsync(this.smtpSettings.Server, this.smtpSettings.Port, this.smtpSettings.UseSsl);
await client.AuthenticateAsync(this.smtpSettings.Username, this.smtpSettings.Password);
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
}
}

View File

@@ -1,7 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MailKit" Version="2.10.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Massmailer.Shared.Model
{
public class SmtpSettings
{
public string Server { get; set; }
public int Port { get; set; }
public string SenderName { get; set; }
public string SenderEmail { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool UseSsl { get; set; }
}
}

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>