48 lines
1.7 KiB
C#
48 lines
1.7 KiB
C#
using MailKit.Net.Smtp;
|
|
using MimeKit;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace clivelancaster.Services
|
|
{
|
|
public class MailService
|
|
{
|
|
private readonly SmtpSettings _smtpSettings;
|
|
|
|
public MailService(IOptions<SmtpSettings> smtpSettings)
|
|
{
|
|
_smtpSettings = smtpSettings.Value;
|
|
}
|
|
|
|
public async Task SendEmailAsync(string fromEmail, string fromName, string message)
|
|
{
|
|
var emailMessage = new MimeMessage();
|
|
emailMessage.From.Add(new MailboxAddress(_smtpSettings.SenderName, _smtpSettings.SenderEmail));
|
|
emailMessage.To.Add(new MailboxAddress(_smtpSettings.SenderName, _smtpSettings.SenderEmail)); // Send to yourself
|
|
emailMessage.Subject = "Contact Form Message";
|
|
|
|
emailMessage.Body = new TextPart("plain")
|
|
{
|
|
Text = $"From: {fromName} ({fromEmail})\n\nMessage:\n{message}"
|
|
};
|
|
|
|
using (var client = new SmtpClient())
|
|
{
|
|
await client.ConnectAsync(_smtpSettings.Server, _smtpSettings.Port, MailKit.Security.SecureSocketOptions.StartTls);
|
|
await client.AuthenticateAsync(_smtpSettings.Username, _smtpSettings.Password);
|
|
await client.SendAsync(emailMessage);
|
|
await client.DisconnectAsync(true);
|
|
}
|
|
}
|
|
}
|
|
|
|
public class SmtpSettings
|
|
{
|
|
public required string Server { get; set; }
|
|
public int Port { get; set; }
|
|
public required string SenderName { get; set; }
|
|
public required string SenderEmail { get; set; }
|
|
public required string Username { get; set; }
|
|
public required string Password { get; set; }
|
|
public bool UseSSL { get; set; }
|
|
}
|
|
} |