Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been trying to figure out the easiest way of sending a confirmation email for when a user signs in!

I am using MailKit and Mailtrap.io (Sqlite and EF).
Below I have an example of the way I am doing it, and I can copy this the same way I have created it below onto my user controller. (I will put in the "What have you tried user controller"

My serviceSb looks like This:


C#
public bool SendMail(string name, string email, string subject, string body)
        {
            var mailMessage = new MimeMessage();
            mailMessage.From.Add(new MailboxAddress("TheMailTrap", "manager@TheMailTrap.com"));
            mailMessage.To.Add(new MailboxAddress(name, email));
            mailMessage.Subject = subject;
            mailMessage.Body = new TextPart("plain")
            {
                Text = body
            };

            try
            {
                var smtpClient = new SmtpClient();
                smtpClient.Connect("smtp.mailtrap.io", 2525, SecureSocketOptions.StartTls);
                smtpClient.Authenticate("61618d4d83c43242344d", "b5be3640923423434342f2afa"); // replace with your mailtrap.io credentials
                smtpClient.Send(mailMessage);
                smtpClient.Disconnect(true);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


My Controller:

<pre lang="C#">
 public IActionResult Create(Patient u)
        {
            if (svc.IsDuplicateEmailPatient(u.EmailAddress, u.Id))
            {
                //alerting the user that the email address is in use

                ModelState.AddModelError(nameof(u.EmailAddress), "The Email is already in use");
            }


            //Complete POST action and add the user 

            if (ModelState.IsValid)
            {
                svc.AddPatient(u);

                // send patient an email to confirm account. Add whatever message you want
                if (!svc.SendMail(u.Name, u.EmailAddress, "New Account", "THIS IS A TEST!!!! :D "))
                {
                    Alert("Email Not Sent", AlertType.warning);
                }
                else
                {
                    Alert("User Was Created. Email sent", AlertType.success); //alert successful
                }

                return RedirectToAction(nameof(Index));

      

            }

            return View(u); // Return if validation errors has occured 
        }



I am looking online at tutorials on how to do this but it is very different from the way I have been taught to implement this. I essentially want to make sure when someone registers into a particular role I want them to be made to wait before "Approved" by the manager - To make sure the role they register for is true!

However, if they register as a patient, for example, a confirmation email is sent and they can confirm it themselves.

Does anyone know the cleanest way of doing this? - My level of coding is a beginner and I have been losing days on looking at ways I think will work and then fails.

What I have tried:

Startup.cs

services.AddIdentity<User, IdentityRole>(opt =>
{
    opt.Password.RequiredLength = 7;
    opt.Password.RequireDigit = false;
    opt.Password.RequireUppercase = false;

    opt.User.RequireUniqueEmail = true;

    opt.SignIn.RequireConfirmedEmail = true;
});



User Controller - This is where I am not sure how to implement the code?

[HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Register([Bind("Name,Email,Password,PasswordConfirm,Role")] UserRegisterViewModel m)       
        {
            if (!ModelState.IsValid)
            {
                return View(m);
            }
            // add user via service
            var user = _svc.AddUser(m.Name, m.Email,m.Password, m.Role);
            // check if error adding user and display warning

            if (user == null) {
                Alert("There was a problem Registering. Please try again", AlertType.warning);
                return View(m);
            }

            Alert("Successfully Registered. Now login", AlertType.info);

            return RedirectToAction(nameof(Login));
        }
Posted
Updated 30-Jul-21 11:07am
v3
Comments
Code Fan 30-Jul-21 17:30pm    
When you step through your SendMail method, do you get any exception? It works but no email gets sent?
MrRobot2021 1-Aug-21 15:12pm    
The email does send but it sends to my dummy account aka mailtrap.Io
Code Fan 1-Aug-21 15:54pm    
You mean it doesn't care about the To field you set? It always sends to your dummy account no matter what? This is not a code issue. Please involve your IT to investigate your mail server setup.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900