Wednesday, April 25, 2012

Send Mail in asp.net using c#

Send Mail in asp.net using c#:

The following code snippet is used to send an email in asp.net using c#. The code itself is self explanatory. The comments in the code help you to understand the code.


protected void btnmail_Click(object sender, EventArgs e)
    {
        // System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
        // System.Net.Mail.SmtpClient is the alternate class for this in 2.0
        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();

        try
        {
            MailAddress fromAddress = new MailAddress("someone@gmail.com","username");

            // You can specify the host name or ipaddress of your server
            // Default in IIS will be localhost
            smtpClient.Host = "smtp.gmail.com";

            //Default port will be 25
            smtpClient.Port = 587;

            //From address will be given as a MailAddress Object
            message.From = fromAddress;
            NetworkCredential credential = new NetworkCredential();
            credential.UserName = "username";
            credential.Password = "password";
            smtpClient.Credentials = credential;
            smtpClient.EnableSsl = true;

            // To address collection of MailAddress
            message.To.Add(txttomail.Text);
            message.Subject = Getdata();


            //Body can be Html or text format
            //Specify true if it  is html message
            message.IsBodyHtml = true

            // Message body content
            message.Body = txtsubject.Text;

            // Send SMTP mail
            smtpClient.Send(message);

          
        }
        catch (Exception ex)
        {

        }
    }

1 comment:

  1. not working, getting the following error-

    System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 74.125.141.108:465 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)

    ReplyDelete