69 lines
2.0 KiB
C#
69 lines
2.0 KiB
C#
using Microsoft.Extensions.Options;
|
|
using MimeKit.Text;
|
|
using MimeKit;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using MailKit.Net.Smtp;
|
|
using Microsoft.AspNetCore.Identity.UI.Services;
|
|
|
|
namespace StockMan.Data
|
|
{
|
|
/// Implementazione interfaccia email con pacchetto MailKIT
|
|
///
|
|
/// https://www.ryadel.com/en/asp-net-core-send-email-messages-smtp-mailkit/
|
|
/// </summary>
|
|
public class MailKitEmailSender : IEmailSender
|
|
{
|
|
#region Public Constructors
|
|
|
|
public MailKitEmailSender(IOptions<MailKitEmailSenderOptions> options)
|
|
{
|
|
this.Options = options.Value;
|
|
}
|
|
|
|
#endregion Public Constructors
|
|
|
|
#region Public Properties
|
|
|
|
public MailKitEmailSenderOptions Options { get; set; }
|
|
|
|
#endregion Public Properties
|
|
|
|
#region Public Methods
|
|
|
|
public Task Execute(string to, string subject, string message)
|
|
{
|
|
// create message
|
|
var email = new MimeMessage();
|
|
email.Sender = MailboxAddress.Parse(Options.Sender_EMail);
|
|
if (!string.IsNullOrEmpty(Options.Sender_Name))
|
|
email.Sender.Name = Options.Sender_Name;
|
|
email.From.Add(email.Sender);
|
|
email.To.Add(MailboxAddress.Parse(to));
|
|
email.Subject = subject;
|
|
email.Body = new TextPart(TextFormat.Html) { Text = message };
|
|
|
|
// send email
|
|
using (var smtp = new SmtpClient())
|
|
{
|
|
smtp.Connect(Options.Host_Address, Options.Host_Port, Options.Host_SecureSocketOptions);
|
|
smtp.Authenticate(Options.Host_Username, Options.Host_Password);
|
|
smtp.Send(email);
|
|
smtp.Disconnect(true);
|
|
}
|
|
|
|
return Task.FromResult(true);
|
|
}
|
|
|
|
public Task SendEmailAsync(string email, string subject, string message)
|
|
{
|
|
return Execute(email, subject, message);
|
|
}
|
|
|
|
#endregion Public Methods
|
|
}
|
|
}
|