yavsc/src/Yavsc/Services/MailSender.cs

90 lines
3.2 KiB
C#
Raw Normal View History

using System;
using System.Net;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using MimeKit;
using Yavsc.Abstract.Manage;
namespace Yavsc.Services
{
public class MailSender : IEmailSender
{
2020-09-12 01:11:30 +01:00
readonly SiteSettings siteSettings;
readonly SmtpSettings smtpSettings;
2023-03-19 16:02:50 +00:00
private readonly ILogger logger;
public MailSender(
IOptions<SiteSettings> sitesOptions,
2023-03-19 16:02:50 +00:00
IOptions<SmtpSettings> smtpOptions,
ILoggerFactory loggerFactory
)
{
siteSettings = sitesOptions?.Value;
smtpSettings = smtpOptions?.Value;
2023-03-19 16:02:50 +00:00
logger = loggerFactory.CreateLogger<MailSender>();
}
/// <summary>
///
/// </summary>
/// <param name="googleSettings"></param>
/// <param name="registrationId"></param>
/// <param name="ev"></param>
/// <returns>a MessageWithPayloadResponse,
/// <c>bool somethingsent = (response.failure == 0 &amp;&amp; response.success > 0)</c>
/// </returns>
public async Task<EmailSentViewModel> SendEmailAsync(string username, string email, string subject, string message)
{
EmailSentViewModel model = new EmailSentViewModel{ EMail = email };
try
{
2023-03-19 16:02:50 +00:00
logger.LogInformation($"SendEmailAsync for {email}: {message}");
MimeMessage msg = new MimeMessage();
msg.From.Add(new MailboxAddress(
siteSettings.Owner.Name,
siteSettings.Owner.EMail));
msg.To.Add(new MailboxAddress(username, email));
msg.Body = new TextPart("plain")
{
Text = message
};
msg.Subject = subject;
msg.MessageId = MimeKit.Utils.MimeUtils.GenerateMessageId(
siteSettings.Authority
);
using (SmtpClient sc = new SmtpClient())
{
sc.Connect(
smtpSettings.Host,
smtpSettings.Port,
SecureSocketOptions.Auto);
2023-03-19 16:02:50 +00:00
if (smtpSettings.UserName!=null) {
NetworkCredential creds = new NetworkCredential(
smtpSettings.UserName, smtpSettings.Password, smtpSettings.Domain);
await sc.AuthenticateAsync(System.Text.Encoding.UTF8, creds, System.Threading.CancellationToken.None);
}
2018-07-16 02:38:09 +02:00
await sc.SendAsync(msg);
model.MessageId = msg.MessageId;
model.Sent = true; // a duplicate info to remove from the view model, that equals to MessageId == null
2023-03-19 16:02:50 +00:00
logger.LogInformation($"Sent : {msg}");
}
}
catch (Exception ex)
{
model.Sent = false;
model.ErrorMessage = ex.Message;
return model;
}
return model;
}
}
}