How to create a "contact us" page

Coreysan 1,696 Reputation points
2022-10-24T19:10:11.547+00:00

I need to learn how to create a "contact us" page for an online store. This is so customers can just email my gmail account with questions, etc.

I have C# code from a tutorial about 4 years old that uses SendGrid, but the version has increased so much that the tutorial won't run.

So while I work on that, is there a simple way do this? Maybe point me in the right direction and I'll read/study it when I'm at home. The SendGrid
solution may be simple, but I'm not sure.

I've read up on MS MailMessage class, and SmtpClient, and have yet to read through Webmail. I'm limited because my box at work is locked down,
so I can only test a little bit.

Thanks for any help or suggestions!

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,553 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,326 Reputation points Microsoft Vendor
    2022-10-25T06:27:25.623+00:00

    Hi @Coreysan ,

    I don't recommend that you use the SmtpClient class for new development because SmtpClient doesn't support many modern protocols. Try to use MailKit, SendGrid or other libraries instead.

    Here is a sample about using MailKit to send email, you can refer to it.

    1. Create an Asp.net 3.1 MVC application, and install the MailKit package (you can also try to use the NETCore.Mailkit package, I checked it on Asp.net 6 application, it also works well) via the Nuget Package Manager.
      253722-image.png
    2. Create a MailRequest model. Then we can according to it to create a page and let use enter the Email address and Email content.
      public class MailRequest  
      {   
          public string ToEmail { get; set; }  
          public string Subject { get; set; }  
          public string Body { get; set; }  
          public List<IFormFile> Attachments { get; set; }  
      }  
      
    3. Create a MailSettings model. We can use it define mail settings.
      public class MailSettings  
      {  
          public string Mail { get; set; }  
          public string DisplayName { get; set; }  
          public string Password { get; set; }  
          public string Host { get; set; }  
          public int Port { get; set; }  
      }  
      
    4. Configure the Mail Setting in AppSetting.Json, since I will send the email using my Hotmail account, the SMTP Host will be "smtp.office365.com", and the port is 587, you can change them based on your email account. Refer to POP, IMAP, and SMTP settings
        "MailSettings": {  
          "Mail": "yourEmail@......COM",  
          "DisplayName": "Your Brand Name",  
          "Password": "YourPassword",  
          "Host": "SMTP Host",  
          "Port": 587  
        },  
      
    5. Create a IMailService and MailService, and add the SendMail methods:
      //using Microsoft.Extensions.Options;  
      //using MimeKit;  
      //using MailKit.Security;  
      //using MvcApp3_1.Models;  
      //using MailKit.Net.Smtp;  
      //using System.IO;  
      //using System.Threading.Tasks;  
      public interface IMailService  
      {  
          Task SendEmailAsync(MailRequest mailRequest);  
      }  
      public class MailService : IMailService  
      {  
          private readonly MailSettings _mailSettings;  
          public MailService(IOptions<MailSettings> mailSettings)  
          {  
              _mailSettings = mailSettings.Value;  
          }  
          public async Task SendEmailAsync(MailRequest mailRequest)  
          {  
              var email = new MimeMessage();  
              email.Sender = MailboxAddress.Parse(_mailSettings.Mail);  
              email.To.Add(MailboxAddress.Parse(mailRequest.ToEmail));  
              email.Subject = mailRequest.Subject;  
              var builder = new BodyBuilder();  
              if (mailRequest.Attachments != null)  
              {  
                  byte[] fileBytes;  
                  foreach (var file in mailRequest.Attachments)  
                  {  
                      if (file.Length > 0)  
                      {  
                          using (var ms = new MemoryStream())  
                          {  
                              file.CopyTo(ms);  
                              fileBytes = ms.ToArray();  
                          }  
                          builder.Attachments.Add(file.FileName, fileBytes, ContentType.Parse(file.ContentType));  
                      }  
                  }  
              }  
              builder.HtmlBody = mailRequest.Body;  
              email.Body = builder.ToMessageBody();  
              using var smtp = new SmtpClient();  
              smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls);  
              smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password);  
              await smtp.SendAsync(email);  
              smtp.Disconnect(true);  
          }  
      }  
      
    6. In the Startup.cs or Program.cs file, register the MailService:
          services.Configure<MailSettings>(Configuration.GetSection("MailSettings"));   
          services.AddScoped<MvcApp3_1.Services.IMailService, MvcApp3_1.Services.MailService>();  
      
    7. In the Controller, create the endpoint to send mail:
      public class HomeController : Controller  
      {  
          private readonly ILogger<HomeController> _logger;   
          private readonly IMailService _mailService;  
          public HomeController(ILogger<HomeController> logger,  IMailService mailService)  
          {  
              _logger = logger;   
              _mailService = mailService;  
          }  
      
          public IActionResult SendMail()  
          {  
              return View();  
          }  
      
          [HttpPost("SendMail")]  
          public async Task<IActionResult> SendMail(MailRequest request)  
          {  
              try  
              {  
                  await _mailService.SendEmailAsync(request);  
                  return Ok();  
              }  
              catch (Exception ex)  
              {  
      
                  throw ex;  
              }  
      
          }   
      
    8. The SendMail view page like this: 253745-image.png
      After that, running the application, in the SendMail page, we can enter the email path and content.
      253792-image.png

    After clicking the Create button, we can receive the email like this:

    253700-image.png

    If you want to send mail using SendGrid, you can refer to the following tutorials:

    .NET Core App Sending An Email Using SendGrid

    Asp.Net Core create a controller to send emails using SendGrid


    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

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.