0

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("yourclassroomconnection@gmail.com"));
    mail.From = new MailAddress("yourclassroomconnection@gmail.com");
    mail.Subject = "New Order";
    string bodyTemplate = Label2.Text;
    mail.Body = bodyTemplate;
    client.Send(mail);
}

Any idea where I'm going wrong?

Bob
  • 101
  • 1
  • 8
  • 1
    Did you try port 587? – Rajitha Bandara Apr 09 '18 at 01:54
  • No, but I will. I didn't know where to start problem solving – Bob Apr 09 '18 at 01:59
  • Ok I tried that and got this error: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. e46sm13555277qtc.27 - gsmtp – Bob Apr 09 '18 at 02:03
  • with port 587 try this. Enable two-factor authentication and then generate an application-specific password. Use that newly generated password to authenticate via SMTP. – Rajitha Bandara Apr 09 '18 at 02:07
  • Can you help me with that one? You kinda lost me.....I'm pretty new to this – Bob Apr 09 '18 at 02:12
  • I also tried port 25 and got this error: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 209.85.232.109:25 – Bob Apr 09 '18 at 02:13
  • Possible duplicate of [Sending email in .NET through Gmail](https://stackoverflow.com/questions/32260/sending-email-in-net-through-gmail) – VDWWD Apr 09 '18 at 06:53

2 Answers2

1

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("your_email_address@gmail.com");
            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

Rajitha Bandara
  • 663
  • 1
  • 10
  • 15
0

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="yourclassroomconnection@gmail.com"> 
    <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!

noobprogrammer
  • 2,038
  • 3
  • 13
  • 25