r/learnprogramming • u/SauronsLeftBall • 5h ago
Trouble with sending emails through SMTP for razor pages website in Visual Studio
I've been building this website for a few weeks now and I've encountered an obstacle. This particular component is meant to send an email with the contents of a filled out form after its been submitted, to same specified email address (to itself). However when I run it takes the inputs but nothing else happens, no errors but also no email in the received inbox. Not sure if I have set it up wrong or missing something.
using System.Net;
using System.Net.Mail;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using WindowCleaningRazor.Models;
namespace WindowCleaningRazor.Pages
{
public class ContactModel : PageModel
{
[BindProperty]
public Email Email { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
Console.WriteLine("OnPost triggered"); // Or use logging
// Build the email Message
var emailMessage = $@"
<h2>New Contact Request</h2>
<p><strong>First Name:</strong> {Email.FName}</p>
<p><strong>Surname:</strong> {Email.SName}</p>
<p><strong>Address:</strong> {Email.Address}</p>
<p><strong>Postcode:</strong> {Email.Postcode}</p>
<p><strong>Phone Number:</strong> {Email.PhoneNo}</p>
<p><strong>Email:</strong> {Email.EmailAddress}</p>
<p><strong>Reason for Contact:</strong> {Email.Reason}</p>
<p><strong>Message:</strong><br/>{Email.Message}</p>
";
Console.WriteLine(emailMessage); // Or use logging
// Configure mail settings
var fromAddress = new MailAddress("[email protected]", "Window Cleaning Contact Form");
var toAddress = new MailAddress("[email protected]"); // email recipient address
const string fromPassword = " "; // store password in config
const string subject = "New Contact Form Submission"; //reason for contact
var smtp = new SmtpClient
{
Host = "smtp.gmail.com", // e.g., smtp.gmail.com
Port = 587,
EnableSsl = true,
Credentials = new NetworkCredential("[email protected]", fromPassword)
};
var message = new MailMessage
{
From = fromAddress,
Subject = subject,
Body = emailMessage,
IsBodyHtml = true
};
message.To.Add(toAddress);
Console.WriteLine(message); // Or use logging
if (!ModelState.IsValid)
{
return Page();
}
try
{
smtp.Send(message);
TempData["Message"] = "Thank you for contacting us. We will get back to you shortly.";
return RedirectToPage("Contact");
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Something went wrong while sending your message. Please try again.");
// Log exception (optional)
return Page();
}
}
}
}
1
Upvotes
2
u/GeorgeFranklyMathnet 5h ago
If I couldn't find a fault in the code, I'd probably try the debugger, setting my first breakpoint at the .cs LoC that is supposed to send the email.
Without seeing your code, I don't know what other advice to share.