Send Email in Asp.net MVC
In this article we will send smtp email
Step 1
Add the following in web.config file
<appSettings> <add key="email" value="example@gmail.com" /> <add key="password" value="password@" /> <add key="smtp" value="smtp.gmail.com" /> <add key="port" value="587" /> </appSettings> |
Step 2
Add the following code to your controller
public static string SendSmtpEmail(string sentTo, string mailSubject, string mailBody) { string from = ConfigurationManager.AppSettings["email"].ToString(); string pass = ConfigurationManager.AppSettings["password"].ToString(); string smtp = ConfigurationManager.AppSettings["smtp"].ToString(); string port = ConfigurationManager.AppSettings["port"].ToString(); MailMessage mail = new MailMessage(from, sentTo); using (SmtpClient client = new SmtpClient()) { client.Port = Convert.ToInt32(port); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(from, pass); client.EnableSsl = false; client.Host = smtp; mail.Subject = mailSubject; mail.Body = mailBody; mail.IsBodyHtml = true; try { client.Send(mail); return "success"; } catch (Exception ex) { return ex.Message; } } }
Step 3
Call SendSmtpEmail function where you want to send email to user
Guid guid = Guid.NewGuid(); string emailBody = string.Format( @"Mr/Ms. {0}, <br/> Thank you for registering to ABC. Please <a href='localhost:5490/?token_number={1}' target='_blank'> click here<a/> to verify and activate your account. <br>Your account will not be activated until your email address is confirmed.<br><br>" ,model.user_name, guid.ToString() ); string msg = sendSmtpEmail(model.email, "ABC Account Activation", emailBody); if (msg != "success") { ModelState.AddModelError("user_email_address", "Email address is not valid"); return View(model); }
Send Smtp Email
public string SendEmail(string emailTo) { string from = "sender@mail.com"; string pass = "password"; string smtp = "smtp.gmail.com"; string port = 587; emailTo="reciever@mailcom" string result = null; try { SmtpClient client = new SmtpClient(); client.EnableSsl = true; client.Port = Port; client.Host = smpt; client.Timeout = 10000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Credentials = new NetworkCredential(from, pass); client.UseDefaultCredentials = true; MailMessage message = new MailMessage(); message.From = new MailAddress(from); message.Subject = "Enter code"; message.Body = string.Format( @"<p>Following are your login details</p> <p><strong>Two Factor Authentication</strong><strong>: </strong></p>" ); message.To.Add(emailTo); message.IsBodyHtml = true; message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; client.Send(message); } catch (Exception ex) { result = ex.Message; } return result; }
0 Comments