MailMessage mailMess = new MailMessage ();
mailMess.From = “abc@gmail.com”;
mailMess.To = “xyz@gmail.com”;
mailMess.Subject = “Test email”;
mailMess.Body = “Hi This is a test mail.”;
SmtpMail.SmtpServer = “localhost”;
SmtpMail.Send (mailMess);
MailMessage and SmtpMail are classes defined System.Web.Mail namespace.
To send an email from an ASP.NET application, you can use the SmtpClient
class available in the System.Net.Mail
namespace. Here’s an example code snippet:
using System.Net;
using System.Net.Mail;
public void SendEmail(string recipient, string subject, string body)
{
try
{
// Set up SMTP client
SmtpClient smtpClient = new SmtpClient("smtp.example.com"); // Change to your SMTP server address
smtpClient.Port = 587; // Change to the port your SMTP server uses
smtpClient.UseDefaultCredentials = false; // Make sure to set appropriate credentials if needed
smtpClient.Credentials = new NetworkCredential("your_username", "your_password"); // Change to your SMTP credentials
smtpClient.EnableSsl = true; // Change accordingly if SSL is required
// Create the email message
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("your_email@example.com"); // Change to the sender email address
mailMessage.To.Add(recipient);
mailMessage.Subject = subject;
mailMessage.Body = body;
// Send the email
smtpClient.Send(mailMessage);
}
catch (Exception ex)
{
// Handle any exceptions
Console.WriteLine("An error occurred: " + ex.Message);
}
}
In this code:
- Replace
"smtp.example.com"
with your SMTP server address. - Replace
587
with the appropriate port number for your SMTP server. The standard ports are587
for TLS/STARTTLS and465
for SSL. - Replace
"your_username"
and"your_password"
with your SMTP server credentials. - Replace
"your_email@example.com"
with the sender email address. - Pass the recipient email, subject, and body to the
SendEmail
method when you call it.
Make sure to handle exceptions appropriately, such as network failures or invalid SMTP server credentials. Additionally, consider configuring your SMTP server and ASP.NET application to handle email delivery properly, such as setting up SPF/DKIM records, ensuring the SMTP server is accessible from your application environment, and handling email sending failures gracefully.