using Microsoft.AspNetCore.Mvc; using System.Net; using clivelancaster.Models; using MailKit.Net.Smtp; using MimeKit; namespace clivelancaster.Controllers { public class ContactController : Controller { public IActionResult Index() { return View(); } private readonly IConfiguration _configuration; public ContactController(IConfiguration configuration) { _configuration = configuration; } [HttpPost] public async Task Index(ContactFormModel model) { if (ModelState.IsValid) { // Build the email message var message = new MimeMessage(); message.From.Add(new MailboxAddress("Clive", "clivelancaster@gmail.com")); message.To.Add(new MailboxAddress("Clive", "clivelancaster@gmail.com")); message.Subject = "Website: Contact Form - clivelancaster.com"; var bodyBuilder = new BodyBuilder { TextBody = $"Name: {model.Name}\nEmail: {model.Email}\n\nSubject: {model.Subject}\n\nMessage:\n{model.Message}" }; message.Body = bodyBuilder.ToMessageBody(); try { using (var client = new SmtpClient()) { // Retrieve SMTP settings from appsettings.json var smtpHost = _configuration["SmtpSettings:Host"]; int smtpPort = int.Parse(s: _configuration["SmtpSettings:Port"]); var smtpUsername = _configuration["SmtpSettings:Username"]; var smtpPassword = _configuration["SmtpSettings:Password"]; client.Connect(smtpHost, smtpPort, true); client.Authenticate(smtpUsername, smtpPassword); await client.SendAsync(message); client.Disconnect(true); } ViewBag.Message = "Message sent successfully!"; } catch { ViewBag.Message = "Error sending message."; } return View(); } return View(model); } } }