Add project files.
This commit is contained in:
68
Controllers/ContactController.cs
Normal file
68
Controllers/ContactController.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
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<IActionResult> 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 = model.Subject;
|
||||
|
||||
var bodyBuilder = new BodyBuilder
|
||||
{
|
||||
TextBody = $"Name: {model.Name}\nEmail: {model.Email}\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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user