Bob
Bob

Reputation: 91

C# Email with Button_Click Event

I'm trying to create a Button_Click event that sends an email to a gmail account. This is the error I'm getting:

Unable to read data from the transport connection: net_io_connectionclosed.

It's pointing out Line 63 which is:

client.Send(mail);

Here is the code:

protected void Button2_Click(object sender, EventArgs e)
{
    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
    SmtpClient client = new SmtpClient();
    client.Port = 465;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Host = "smtp.gmail.com";
    mail.IsBodyHtml = true;
    mail.To.Add(new MailAddress("[email protected]"));
    mail.From = new MailAddress("[email protected]");
    mail.Subject = "New Order";
    string bodyTemplate = Label2.Text;
    mail.Body = bodyTemplate;
    client.Send(mail);
}

Any idea where I'm going wrong?

Upvotes: 0

Views: 470

Answers (2)

Rohan Rao
Rohan Rao

Reputation: 2613

Hard coding the username and password (i.e. the credentials) may be sometimes frustrating. What you can do is, you can add these credentials in web.config file only once. And you are good to go. Here is the better solution.

web.config file code goes as follows:

<configuration> 
  <appSettings>
   <add key="receiverEmail" value ="ReceiverEmailAddressHere"/>
  </appSettings>
  </appSettings> 
  <system.net>
  <mailSettings>
  <smtp deliveryMethod="Network" from="[email protected]"> 
    <network host="smtp.gmail.com" port="587" enableSsl="true" 
    userName="YourActualUsername" password="YourActualPassword"/>
  </smtp>
</mailSettings>
</system.net>
</configuration>

Please note that you have to change the host according to your gmail account. I am not sure whether the host is correct. I am using outlook to send emails so the host would be smtp-mail.outlook.com

This is how your web.config file would have all the necessary connection credentials that you define at one place at a time. You don't have to use it everytime you use the Email functionality in your application.

 protected void btnSendMail_Click(object sender, EventArgs e)
{
 MailMessage msg = new MailMessage();
 // get the receiver email address from web.config
 msg.To.Add(ConfigurationManager.AppSettings["receiverEmail"]);


 // get sender email address path from web.config file
 var address = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
 string emailAddress = address.Network.UserName;
 string password = address.Network.Password;
 NetworkCredential credential = new NetworkCredential(emailAddress, password);
 msg.Subject = " Subject text here "
}
  SmtpClient client = new SmtpClient();
  client.EnableSsl = true;  
  client.Send(msg);   // send the message

The key point here is to access the sender's email address and receiver's email address. Note that I have used (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp"); This will navigate your web.config file and search through the hierarchy available in it - Grabs the email address, fails if it doesn't get email address.

Hope this helps. Happy coding!

Upvotes: 0

Rajitha Bandara
Rajitha Bandara

Reputation: 751

You can use below code as a small test. Try sending email with minimal option. Then add other options like html support. So you can narrow down the problem when you're experimenting a new thing.

       try {
        MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress("[email protected]");
            mail.To.Add("to_address");
            mail.Subject = "Test Mail";
            mail.Body = "This is for testing SMTP mail from GMAIL";

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);

        } catch (Exception ex)
        {

        }

You need to generate app specific password and use it here instead of your gmail password.

Please read this tutorial also. http://csharp.net-informations.com/communications/csharp-smtp-mail.htm

Upvotes: 1

Related Questions