top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

code to send e-mail from an ASP.NET application

+3 votes
98 views

I have to Write a code to send e-mail from an ASP.NET application. Can anyone help with that.

posted Aug 20, 2014 by Muskan

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes
 
Best answer

.NET has a namespace to handle emails called System.Net.Mail namespace. As mails are sent through an SMTP server, and to send mails with the .NET framework, you will need access to an SMTP server. If you have an SMTP server which is accessible from your app u can send the mail as follows -

protected void send_email(object sender, EventArgs e)
{
    try
    {
        MailMessage mailMessage = new MailMessage();
        mailMessage.To.Add("To Mail address");
        mailMessage.From = new MailAddress("Your Mail Address");
        mailMessage.Subject = "Your Subject";
        mailMessage.Body = "Body of the email";
        SmtpClient smtpClient = new SmtpClient("smtp.your-isp.com");
        smtpClient.Send(mailMessage);
        Response.Write("E-mail Successfully sent");
    }
    catch(Exception ex)
    {
        Response.Write("Error in sending email " + ex.Message);
    }
}

Attach a file

mailMessage.Attachments.Add(new Attachment(Server.MapPath("<filename>")));

Add more then one person

mailMessage.To.Add("First email address");
mailMessage.To.Add("Another email address");

Setting the sender name

mailMessage.From = new MailAddress("Your address", "Your Name");

Sending HTML Mail

mailMessage.IsBodyHtml = true;

Adding CC and BCC

mailMessage.CC.Add("CC Address");
mailMessage.Bcc.Add("BCC Address");
answer Aug 20, 2014 by Salil Agrawal
...