03 March, 2014

How to send email in ASP.net

Please click the link and view the post new domain : http://mahedee.net instead of this. I am not updating blog here. I am writing and updating blog in http://mahedee.net

You have to configure SMTP server before sending email from your server. Hope you already know how to configure smtp server. Here is the simple code segment for sending email against a button click.

 protected void btnSendMail_Click(object sender, EventArgs e)
    {
      
        SmtpClient smtpClient = new SmtpClient(); 
        MailAddress fromAddress = new MailAddress("mahedee_hasan@leads-bd.com"); //Sender email address
        MailMessage _mail = new MailMessage();

       _mail.Attachments.Add(new Attachment(@"E:\Temp\attachment.pdf")); //Add dirctory of attachment
         
        
        //bool IsSuccess = false;
        try
        {
            _mail.From = fromAddress; 
            _mail.To.Add("mahedee.hasan@gmail.com"); //Receiver email address
            _mail.CC.Add("mahedee.hasan@yahoo.com"); //Email address for cc
            _mail.Bcc.Add("mahedee.hasan@hotmail.com"); //Email address for bcc


            _mail.Subject = "Test Message"; //Email subject
            _mail.Body = "Dear concern, This is the test message from Mahedee"; //Email body
            _mail.IsBodyHtml = true; //Email body is in html format

            smtpClient.Host = "182.268.30.50"; //Name or IP address of the host used for SMTP transaction
            smtpClient.EnableSsl = false;
            //smtpClient.Port = 25; //25 is default port for smtp. You have to change port no if it is not used defualt port 
            smtpClient.Send(_mail);   //Send mail
            //IsSuccess = true;
        }
        catch (Exception ex)
        {
            //IsSuccess = false;
        }
        finally
        {
            //
        }

    }