Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

C# Help with a table that sends an email to a person when submitted

Gaurav

New Coder
I am a very beginner coder who is trying to make a table on C# in which I'm making a requisition slip which a person can enter data on and submit. When the data is submitted the data gets sent to a desired email but i keep getting errors like
"An unhandled exception occurred while processing the request."
How do I fix my code?


using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using Microsoft.Extensions.Logging;

namespace BestStore.Pages
{
public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;

// This will hold the requisition data from the form
[BindProperty]
public List<RequisitionItem> RequisitionItems { get; set; } = new List<RequisitionItem>();

// Added property for the person's name requesting the items
[BindProperty]
public string? Name { get; set; } // Name of the person requesting, nullable

public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;

// Initialize the list of items with 21 empty rows (for 21 products)
for (int i = 0; i < 21; i++)
{
RequisitionItems.Add(new RequisitionItem());
}
}

// OnGet method is executed when the page is first loaded
public void OnGet()
{
}

// This method is triggered when the form is submitted
public IActionResult OnPostSubmit()
{
// Prepare the requisition details to send in the email
var requisitionDetails = "Requisition Slip\n\n";
requisitionDetails += "Name: " + (Name ?? "Not provided") + "\n";
requisitionDetails += "Date: " + DateTime.Now.ToString("yyyy-MM-dd") + "\n\n";

// Loop through the list of requisition items and add their details
foreach (var item in RequisitionItems)
{
requisitionDetails += $"Product: {(item.ProductName ?? "Not provided")}\n";
requisitionDetails += $"Weight: {(item.Weight ?? "Not provided")}\n";
requisitionDetails += $"Type: {(item.Type ?? "Not provided")}\n";
requisitionDetails += $"Quantity Requested: {(item.QuantityRequested?.ToString() ?? "Not provided")}\n";
requisitionDetails += $"Quantity Issued: {(item.QuantityIssued?.ToString() ?? "Not provided")}\n";
requisitionDetails += $"Remarks: {(item.Remarks ?? "Not provided")}\n";
requisitionDetails += "\n";
}

// Send the requisition details to the email address
SendEmail("[email protected]", "Requisition Slip", requisitionDetails);

// Redirect to a Thank You page or a success message
return RedirectToPage("Index"); // Make sure you have a ThankYou page or handle the response
}

// Method to send the requisition data via email using Gmail SMTP
private void SendEmail(string toEmail, string subject, string body)
{
try
{
var fromEmail = "[email protected]"; // Replace with your Gmail address
var appPassword = "your-app-password"; // Replace with the App Password generated for Gmail

var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential(fromEmail, appPassword), // Gmail credentials
EnableSsl = true,
};

var mailMessage = new MailMessage
{
From = new MailAddress(fromEmail),
Subject = subject,
Body = body,
IsBodyHtml = false, // Set to true if you're sending HTML emails
};
mailMessage.To.Add(toEmail);

// Send the email
smtpClient.Send(mailMessage);
}
catch (Exception ex)
{
// Log the error or handle the failure case (e.g., show a message to the user)
_logger.LogError("Error sending email: " + ex.Message);
}
}
}

// Class to represent a single requisition item (row in the table)
public class RequisitionItem
{
// Nullable strings - No changes needed for these properties
public string? ProductName { get; set; } // Nullable string
public string? Weight { get; set; } // Nullable string
public string? Type { get; set; } // Nullable string
public string? Remarks { get; set; } // Nullable string

// Nullable integers for quantities
public int? QuantityRequested { get; set; } // Nullable integer
public int? QuantityIssued { get; set; } // Nullable integer
}
}
 
Sorry for the late response.

Possible Issues & Fixes​

  1. SMTP Configuration Issue (Email Sending Error)
    • You need to ensure that your Gmail account allows "Less Secure Apps" or use an App Password (which you’ve mentioned, but ensure it's valid).
    • If there’s an issue with SMTP (like incorrect credentials, port, or SSL), it can cause an exception.
    • Solution: Try using smtpClient.SendAsync(mailMessage, null) instead of smtpClient.Send(mailMessage) for better debugging.
  2. Logging More Details About Exceptions
    • Instead of just logging ex.Message, log the entire stack trace:
      C#:
      _logger.LogError($"Error sending email: {ex}");
  3. Ensure The Form Data is Passed Correctly
    • Check if RequisitionItems is properly populated when OnPostSubmit() is called.
    • If it’s null, it means the form isn’t binding correctly.
  4. Improve Debugging: Add Try-Catch for OnPostSubmit
C#:
public IActionResult OnPostSubmit()
{
    try
    {
        // Prepare the email
        var requisitionDetails = $"Requisition Slip\n\nName: {(Name ?? "Not provided")}\nDate: {DateTime.Now:yyyy-MM-dd}\n\n";
        
        foreach (var item in RequisitionItems)
        {
            requisitionDetails += $"Product: {(item.ProductName ?? "Not provided")}\n";
            requisitionDetails += $"Quantity: {(item.QuantityRequested?.ToString() ?? "Not provided")}\n\n";
        }

        SendEmail("[email protected]", "Requisition Slip", requisitionDetails);
        return RedirectToPage("Index");
    }
    catch (Exception ex)
    {
        _logger.LogError($"An error occurred: {ex}");
        ModelState.AddModelError("", "Something went wrong. Please try again.");
        return Page();
    }
}

Let me know if this helps. If not we can go back to the drawing board.
 
Back
Top Bottom