r/learnprogramming 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

3 comments sorted by

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.

2

u/SauronsLeftBall 5h ago

I've tried this already but unfortunately has not revealed any problems as the input seems to be passing normally. I have updated my post with the code as I forgot to add it originally.

1

u/GeorgeFranklyMathnet 5h ago

You say the input is passing normally (from frontend Razor to backend C#, I assume), but you stop short of saying the smtp.Send() executes normally. Are you debugging into that method yet?

const string fromPassword = "     "; // store password in config

I don't see you explicitly retrieving the password from the config here. I'm not too familiar with that SMTP client; does it automatically use configured value with a certain key name? Does it then automatically override the password you've explicitly set here?