How to made speedy send mail in mvc4
To send an email quickly in an MVC4 application, you can use the System.Net.Mail
namespace. Here's a step-by-step guide:
Step 1: Create a new MailMessage object
Create a new instance of the MailMessage
class and set the properties:
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Email";
mail.Body = "This is a test email";
Step 2: Create a new SmtpClient object
Create a new instance of the SmtpClient
class and set the properties:
SmtpClient client = new SmtpClient();
client.Host = "your-smtp-server";
client.Port = 587; // or 25, depending on your SMTP server
client.EnableSsl = true; // if your SMTP server requires SSL
client.Credentials = new NetworkCredential("[email protected]", "your-password");
Step 3: Send the email
Use the Send
method of the SmtpClient
object to 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()
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Email";
mail.Body = "This is a test email";
SmtpClient client = new SmtpClient();
client.Host = "your-smtp-server";
client.Port = 587; // or 25, depending on your SMTP server
client.EnableSsl = true; // if your SMTP server requires SSL
client.Credentials = new NetworkCredential("[email protected]", "your-password");
client.Send(mail);
return RedirectToAction("EmailSent");
}
public ActionResult EmailSent()
{
return View();
}
}
Tips and Variations
- You can add attachments to the email by using the
Attachments
property of theMailMessage
object. - You can set the priority of the email by using the
Priority
property of theMailMessage
object. - You can use a different SMTP server by changing the
Host
andPort
properties of theSmtpClient
object. - You can use a different email address for the
From
property by changing theMailAddress
object. - You can use a different email address for the
To
property by adding multipleMailAddress
objects to theTo
collection.