Files
raven/server/AyaNova/util/Mailer.cs
2022-03-05 23:35:11 +00:00

74 lines
2.9 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);
}
public class Mailer : IMailer
{
public Mailer()
{
}
public async Task SendEmailAsync(string email, string subject, string body, AyaNova.Models.GlobalOpsNotificationSettings smtpSettings, string attachPDFPath = 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("test.pdf")
//FileName = Path.GetFileName(attachPDFPath)
};
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);
}
}
catch (Exception e)
{
throw new InvalidOperationException(e.Message);
}
}
}
}