Files
raven/server/AyaNova/util/Mailer.cs
2022-03-08 22:55:15 +00:00

81 lines
3.2 KiB
C#

using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Threading.Tasks;
using MimeKit.Text;
using System.IO;
namespace AyaNova.Util
{
public interface IMailer
{
Task SendEmailAsync(string email, string subject, string body, AyaNova.Models.GlobalOpsNotificationSettings smtpSettings, string attachPDF = null, string forceFileName = null);
}
public class Mailer : IMailer
{
public Mailer()
{
}
public async Task SendEmailAsync(string email, string subject, string body, AyaNova.Models.GlobalOpsNotificationSettings smtpSettings, string attachPDFPath = null, string forceFileName = null)
{
try
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(smtpSettings.NotifyFromAddress, smtpSettings.NotifyFromAddress));
message.To.Add(MailboxAddress.Parse(email));
message.Subject = subject;
if (!string.IsNullOrWhiteSpace(attachPDFPath))
{
var attachment = new MimePart("application/pdf", "pdf")
{
Content = new MimeContent(File.OpenRead(attachPDFPath), ContentEncoding.Default),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName(attachPDFPath)
};
if (!string.IsNullOrWhiteSpace(forceFileName))
attachment.FileName = forceFileName;
var multipart = new Multipart("mixed");
if (!string.IsNullOrWhiteSpace(body))
multipart.Add(new TextPart(TextFormat.Plain) { Text = body });
multipart.Add(attachment);
message.Body = multipart;
}
else
{
if (!string.IsNullOrWhiteSpace(body))
message.Body = new TextPart(TextFormat.Plain) { Text = body };
}
using (var client = new SmtpClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
bool UseSSL = smtpSettings.ConnectionSecurity != Biz.NotifyMailSecurity.None;
await client.ConnectAsync(smtpSettings.SmtpServerAddress, smtpSettings.SmtpServerPort, UseSSL);
await client.AuthenticateAsync(smtpSettings.SmtpAccount, smtpSettings.SmtpPassword);
await client.SendAsync(message);
await client.DisconnectAsync(true);
DisposeStreamsInMimeMessage(message);
}
}
catch (Exception e)
{
throw new InvalidOperationException(e.Message);
}
}
public static void DisposeStreamsInMimeMessage(MimeMessage msg) { foreach (var part in msg.BodyParts) (part as MimePart)?.Content?.Stream?.Dispose(); }
}
}