retrieving form data by email using asp.net core razor

Nigel 271 Reputation points
2023-03-14T14:22:19.8433333+00:00

I have a form in my asp.net core Razor web app. I want the contents of the form to be sent back to me via email. Code I have so far is on the razor page:

<div class="col-4">

<form method="post">

<div class="mb-3">

<label for="name">Name: </label>

<input class="form-control" type="text" name="Name" />

<label for="email">e-mail: </label>

<input class="form-control" type="email" name="Email" />

<label for="query">Your Query</label>

<input class="form-control" type="text-area" name="Query" />

</div>

<button class="btn btn-primary">Submit</button>

</form>

<p>@Model.message</p>

</div>

and in the code behind (cshtml.cs) model page:

public string message { get; set; }

public void OnPost()

{

if (!StringValues.IsNullOrEmpty(Request.Form["Name"]))

{

message = $"Thank you {Request.Form["Name"]}, we will be in touch by either phone or e-mail.";

}

}

I need to take the input values and convert them to an email (or html) to send to my email through an smtp server.

Any help would be appreciated.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,324 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,118 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 47,461 Reputation points
    2023-03-14T14:39:40.2533333+00:00

    I assume you already have the data retrieved from the client in your razor page. So you just need to send an email. That is done using [SmtpClient](https://learn.microsoft.com/en- us/dotnet/api/system.net.mail.smtpclient?view=net-7.0).

    var client = new SmtpClient();
    var from = new MailAddress("noreply@somewhere.com");
    var to = new MailAddress("someone@somewhere.com");
    var msg = new MailMessage(from, to);
    msg.Subject = "Sending an email";
    msg.Body = "Body of message";
    client.Send(msg);
    

    As for building the message you can use any approach you want depending on what you are trying to do. For a simple message just use a string. If you need to build a formatted message with some simple values then use string interpolation. If you need to format more complex messages then use StringBuilder.

    msg.Body = "Hello";
    
    //More elaborate
    var name = "Bob";
    msg.Body = $"Hello {name}";
    
    //Most complex
    var builder = new StringBuilder();
    builder.Append("Hello ");
    if (isFemale)
       builder.Append("Mrs ");
    else
       builder.Append("Mr ");
    builder.Append(name);
    builder.Append($"You owe us {amount:c}. Please remit");
    
    msg.Body = builder.ToString();
    

1 additional answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,006 Reputation points Microsoft Vendor
    2023-03-15T06:46:52.99+00:00

    Hi @Nigel

    After generating the mail message, you can try to use the following code to send mail using SMTP server:

    //reference:
    using System.Net;    
    using System.Net.Mail; 
    using System.Text;
    
    //code in the post method
            string sender = "sender@hotmail.com"; //sender address    
            string receiver= "receiver@hotmail.com"; //receiver address    
            MailMessage message = new MailMessage(sender, receiver);
    
            //build the mail body and add the hyperlink
            string mailbody = "<h1>Hi <a href= '" + _config.GetSection("contacturl").Value + "' > Contact Us </a> Thank you.</h1>";
            message.Subject = "Contact Us";
    
            //set the mail body format
            message.Body = mailbody;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = true; //
    
            SmtpClient client = new SmtpClient("smtp.live.com", 587); //outlook smtp    
            System.Net.NetworkCredential basicCredential1 = new
            System.Net.NetworkCredential("sender email", "password");
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = basicCredential1;
            try
            {
                client.Send(message);
            }
    
            catch (Exception ex)
            {
                throw ex;
            }
            client.Dispose();
    

    The received email is this:

    User's image

    [Note] In the above sample, I'm sending the email via the outlook email, so when create the SmtpClient instance, I use the outlook smtp and set the port to 587, if you want to send an email using another SMTP Server, you can refer the following table:

    User's image

    Besides, to send email, you can also try to use MailKit, SendGrid or other libraries. Refer to my reply in this thread:

    How to create a "contact us" page


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    1 person found this answer helpful.