Please refer 3 steps to send email.
1. First, set SMTP details in the web.config file under system.net as mentioned below:
//best way to store SMTP details is web.config as it might be changed later on.
<system.net>
<!-- Set SMTP details for Mail-->
<mailSettings>
<smtp>
<network host="smtp.gmail.com" enableSsl="true" userName="put your user name" password="put your password" port="587" />
</smtp>
</mailSettings>
</system.net>
2. Write function to send email.
public bool Send(string from, string to, string subject, string bodyMsg)
{
var message = new MailMessage
{
From = new MailAddress(from),
Subject = subject,
Body = bodyMsg,
IsBodyHtml = true
};
message.To.Add(new MailAddress(to));
message.Bcc.Add(new MailAddress("bccemail@email.com"));//Set if you want to send a blind carbon copy as well to specific address otherwise, comment this line.
try
{
SmtpClient client = new SmtpClient();
client.Send(message);
}
catch (Exception ex)
{
//log your error message
return false;
}
return true;
}
3. Call send method from send action
[HttpPost]
public ActionResult Contact(ContactModels model)
{
if (ModelState.IsValid)
{
//fetch required values from post model
String from = “emailaddress”;
String to = model.to;
String subject = model.subject;
String body = model.body;
bool isSuccess = SendEmail(from, to, subject, body);
if (isSuccess)
{
returnView("Success");
}
else
{
returnView("Error");
}
}
return View();
}
By following above steps you can user send their requirement via email using my web application in asp.net. You can also contact us for any query related to .net problems. Dedicated Asp.Net Developers