56 lines
1.8 KiB
C#
56 lines
1.8 KiB
C#
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.Threading.Tasks;
|
|
|
|
public class SMTPClient
|
|
{
|
|
private readonly SMTPSettings settings;
|
|
|
|
public SMTPClient(SMTPSettings settings)
|
|
=> this.settings = settings;
|
|
|
|
public async Task<bool> SendAsync(string subject, string body, string from, IEnumerable<string> to)
|
|
{
|
|
try
|
|
{
|
|
using (var client = new SmtpClient())
|
|
{
|
|
// await client.AuthenticateAsync(this.settings.Username, this.settings.Password);
|
|
await client.ConnectAsync(this.settings.Host, this.settings.Port);
|
|
|
|
var message = new MimeMessage
|
|
{
|
|
Subject = subject,
|
|
Body = new BodyBuilder
|
|
{
|
|
HtmlBody = body
|
|
}.ToMessageBody(),
|
|
};
|
|
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}" });
|
|
}
|
|
|
|
return true;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
File.AppendAllLines("smtp.log", new[] { $"[SMTP_ERROR] {e.Message}" });
|
|
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|