SMTP clinet from System.Net implemented

This commit is contained in:
Stoyan Zlatev
2023-05-17 15:54:15 +02:00
parent 4ef3651ed7
commit 03ec6fcb77
4 changed files with 39 additions and 20 deletions
@@ -0,0 +1,23 @@
namespace LaaProductionWeb.API.Controllers
{
using LaaProductionWeb.API.Models.SMTP;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
[ApiController]
[Route("[controller]")]
public class EmailController : ControllerBase
{
private readonly SMTPClient smtp;
public EmailController(SMTPClient smtp)
=> this.smtp = smtp;
public async Task<IActionResult> Get()
{
await this.smtp.SendAsync("Test", "It works!!!", "stoyan.zlatev@xylem.com", new[] { "roland.drabesch@xylem.com", "stoyan.zlatev@xylem.com" });
return this.Ok();
}
}
}
@@ -6,7 +6,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MailKit" Version="4.0.0" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.9" />
@@ -1,12 +1,9 @@
namespace LaaProductionWeb.API.Models.SMTP
{
using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Threading.Tasks;
public class SMTPClient
@@ -20,26 +17,26 @@
{
try
{
using (var client = new SmtpClient())
using (var client = new SmtpClient(settings.Host, settings.Port))
{
// await client.AuthenticateAsync(this.settings.Username, this.settings.Password);
await client.ConnectAsync(this.settings.Host, this.settings.Port);
client.Host = this.settings.Host;
client.Port = this.settings.Port;
client.UseDefaultCredentials = true;
var message = new MimeMessage
var message = new MailMessage
{
From = new MailAddress(from),
Subject = subject,
Body = new BodyBuilder
{
HtmlBody = body
}.ToMessageBody(),
Body = body,
IsBodyHtml = true,
};
message.From.Add(MailboxAddress.Parse(from));
message.To.Add(MailboxAddress.Parse(to.FirstOrDefault()));
message.Cc.AddRange(to.Skip(1).Select(x => MailboxAddress.Parse(x)));
var response = await client.SendAsync(message);
File.AppendAllLines("smtp.log", new[] { $"[SMTP_RESPONSE] {response}" });
foreach (var email in to)
{
message.To.Add(email);
}
await client.SendMailAsync(message);
}
return true;
@@ -40,7 +40,7 @@
{
options.SuppressModelStateInvalidFilter = true;
});
services.Configure<SMTPSettings>(this.configuration);
services.Configure<SMTPSettings>(this.configuration.GetSection(nameof(SMTPSettings)));
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Latest);