Files
Plushealthtech/plushealthtech/Pages/Subscribe.cshtml.cs
T
Clive b7809615c7
Gitea CI/CD / build (push) Successful in 1m40s
Connect form email.
2026-08-20 15:55:24 +10:00

65 lines
2.3 KiB
C#

using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using plushealthtech.Mail;
namespace plushealthtech.Pages
{
/// <summary>
/// Handles the footer "Connect" newsletter form (POST /Subscribe).
/// An API-style page handler: success and failure come back as JSON to
/// the layout's inline script; Subscribe.cshtml is an empty view that
/// exists only so the page model is routed.
/// </summary>
public class SubscribeModel : PageModel
{
private readonly MailSender _mailSender;
private readonly ILogger<SubscribeModel> _logger;
public SubscribeModel(MailSender mailSender, ILogger<SubscribeModel> logger)
{
_mailSender = mailSender;
_logger = logger;
}
[BindProperty]
[Required]
[EmailAddress]
[StringLength(320)]
public string Email { get; set; } = string.Empty;
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return new JsonResult(new { success = false, message = "Please enter a valid email address." })
{
StatusCode = StatusCodes.Status400BadRequest
};
}
var body = string.Join("\n", new List<string>
{
$"Email: {Email}",
string.Empty,
"Subscribed from the footer newsletter form (Connect) on the Plus Health Tech website."
});
try
{
await _mailSender.SendAsync($"New newsletter subscription — {Email}", body);
return new JsonResult(new { success = true, message = "You're on the list — thanks for subscribing!" });
}
catch (Exception ex)
{
// Log the full exception; never surface SMTP details to the user.
_logger.LogError(ex, "Failed to send newsletter subscription for {Email}", Email);
return new JsonResult(new { success = false, message = "We couldn't sign you up right now. Please try again later." })
{
StatusCode = StatusCodes.Status500InternalServerError
};
}
}
}
}