Asp net mvc send mail
In ASP.NET MVC, you can send an email using the System.Net.Mail
namespace. Here's a step-by-step guide:
Step 1: Install the necessary NuGet package
In your ASP.NET MVC project, install the System.Net.Mail
NuGet package by running the following command in the Package Manager Console:
Install-Package System.Net.Mail
Step 2: Create a mail message
Create a new instance of the MailMessage
class and set its properties:
using System.Net.Mail;
// Create a new mail message
MailMessage mail = new MailMessage();
// Set the sender's email address
mail.From = new MailAddress("[email protected]");
// Set the recipient's email address
mail.To.Add("[email protected]");
// Set the subject of the email
mail.Subject = "Test Email";
// Set the body of the email
mail.Body = "This is a test email sent using ASP.NET MVC.";
Step 3: Create a mail client
Create a new instance of the SmtpClient
class and set its properties:
using System.Net.Mail;
// Create a new SmtpClient instance
SmtpClient client = new SmtpClient();
// Set the SMTP server's address
client.Host = "smtp.example.com";
// Set the SMTP server's port
client.Port = 587;
// Set the SMTP server's username and password
client.Credentials = new NetworkCredential("your-smtp-username", "your-smtp-password");
Step 4: Send the email
Use the Send
method of the SmtpClient
instance to send the email:
// Send the email
client.Send(mail);
Example code
Here's the complete example code:
using System.Net.Mail;
public class EmailController : Controller
{
public ActionResult SendEmail()
{
// Create a new mail message
MailMessage mail = new MailMessage();
// Set the sender's email address
mail.From = new MailAddress("[email protected]");
// Set the recipient's email address
mail.To.Add("[email protected]");
// Set the subject of the email
mail.Subject = "Test Email";
// Set the body of the email
mail.Body = "This is a test email sent using ASP.NET MVC.";
// Create a new SmtpClient instance
SmtpClient client = new SmtpClient();
// Set the SMTP server's address
client.Host = "smtp.example.com";
// Set the SMTP server's port
client.Port = 587;
// Set the SMTP server's username and password
client.Credentials = new NetworkCredential("your-smtp-username", "your-smtp-password");
// Send the email
client.Send(mail);
// Return a success message
return RedirectToAction("EmailSent");
}
public ActionResult EmailSent()
{
return View();
}
}
Note: Make sure to replace the placeholders ([email protected]
, [email protected]
, smtp.example.com
, your-smtp-username
, and your-smtp-password
) with your actual email addresses and SMTP server settings.