46 lines
1.5 KiB
C#
46 lines
1.5 KiB
C#
using MailKit.Net.Smtp;
|
|
using MimeKit;
|
|
|
|
namespace YAPWebApplication.Infrastructure
|
|
{
|
|
public interface IEmailService
|
|
{
|
|
Task SendEmailAsync(string to, string subject, string body, Stream? attachment = null, string? fileName = null);
|
|
}
|
|
|
|
public class EmailService : IEmailService
|
|
{
|
|
private readonly IConfiguration _config;
|
|
|
|
public EmailService(IConfiguration config)
|
|
{
|
|
_config = config;
|
|
}
|
|
|
|
public async Task SendEmailAsync(string to, string subject, string body, Stream? attachment = null, string? fileName = null)
|
|
{
|
|
var emailMessage = new MimeMessage();
|
|
emailMessage.From.Add(new MailboxAddress("Shop Reports", _config["Email:SmtpUser"]));
|
|
emailMessage.To.Add(MailboxAddress.Parse(to));
|
|
emailMessage.Subject = subject;
|
|
|
|
var builder = new BodyBuilder { HtmlBody = body };
|
|
|
|
if (attachment != null && fileName != null)
|
|
{
|
|
attachment.Seek(0, SeekOrigin.Begin);
|
|
builder.Attachments.Add(fileName, attachment);
|
|
}
|
|
|
|
emailMessage.Body = builder.ToMessageBody();
|
|
|
|
using var client = new SmtpClient();
|
|
await client.ConnectAsync(_config["Email:SmtpServer"], int.Parse(_config["Email:SmtpPort"]), true);
|
|
await client.AuthenticateAsync(_config["Email:SmtpUser"], _config["Email:SmtpPass"]);
|
|
await client.SendAsync(emailMessage);
|
|
await client.DisconnectAsync(true);
|
|
}
|
|
}
|
|
}
|
|
|