67 lines
2.3 KiB
C#
67 lines
2.3 KiB
C#
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using MailKit.Net.Smtp;
|
|
using MimeKit;
|
|
|
|
namespace Email
|
|
{
|
|
public class EmailClient
|
|
{
|
|
private EmailConfiguration EmailConfiguration { get; }
|
|
private IList<string> EmailAttachments { get; set; }
|
|
|
|
public EmailClient(EmailConfiguration emailConfiguration)
|
|
{
|
|
EmailConfiguration = emailConfiguration;
|
|
EmailAttachments = new List<string>();
|
|
}
|
|
|
|
public void SendEmail(string body, bool isHtml = false)
|
|
{
|
|
BodyBuilder bodyBuilder = new BodyBuilder
|
|
{
|
|
HtmlBody = isHtml ? body : null,
|
|
TextBody = !isHtml ? body : null
|
|
};
|
|
|
|
foreach (string attachment in EmailAttachments)
|
|
{
|
|
bodyBuilder.Attachments.Add(attachment);
|
|
}
|
|
|
|
IList<string> emailsTo = EmailConfiguration.EmailTo.Split(',', ';', ' ');
|
|
|
|
MimeMessage mailMessage = new MimeMessage();
|
|
mailMessage.From.Add(MailboxAddress.Parse(EmailConfiguration.EmailFrom));
|
|
mailMessage.To.AddRange(emailsTo.Select(MailboxAddress.Parse));
|
|
mailMessage.Subject = EmailConfiguration.Subject;
|
|
mailMessage.Body = bodyBuilder.ToMessageBody();
|
|
mailMessage.Priority = (MessagePriority)EmailConfiguration.MessagePriority;
|
|
|
|
using (SmtpClient smtpClient = new SmtpClient())
|
|
{
|
|
smtpClient.Connect(EmailConfiguration.Address,
|
|
EmailConfiguration.Port,
|
|
EmailConfiguration.Ssl
|
|
? MailKit.Security.SecureSocketOptions.StartTls
|
|
: MailKit.Security.SecureSocketOptions.None);
|
|
smtpClient.Authenticate(EmailConfiguration.User,
|
|
EmailConfiguration.Password);
|
|
smtpClient.Send(mailMessage);
|
|
smtpClient.Disconnect(true);
|
|
}
|
|
}
|
|
|
|
public void AddAttachment(string attachmentPath)
|
|
{
|
|
if (File.Exists(attachmentPath))
|
|
{
|
|
EmailAttachments.Add(attachmentPath);
|
|
}
|
|
}
|
|
|
|
public void ClearAttachments() => EmailAttachments = new List<string>();
|
|
}
|
|
}
|