Timeout limit trying to send email c # windows forms

1

I'm trying to create an application to send "forgot password" emails but without success so far I posted here a problem where the screen was freezing and gave time to the application, I was told to use background worker, so I'm using more now even though the application continues to give error in the time limit exceeded and does not send anything, not even the progress bar does nothing. NOTE: I changed the password and email fields of the send email function for obvious reasons. Follow the code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Mail;
using MySql.Data.MySqlClient;
using System.Net;

namespace Inicio
{
    public partial class Email : Form
    {
        MySqlConnection con = new MySqlConnection(@"Data Source=localhost;port=3306;Initial Catalog=digital wallet;User ID=root;password=");
        public Email()
        {
            InitializeComponent();
        }

        struct DataParameter
        {
            public int Process;
            public int Delay;
        }

        private DataParameter _inputparameter;

        private void SendEmail()
        {

            if (textBox1.Text == "" || textBox2.Text == "")
            {
                MessageBox.Show("Preencha todos os campos", "Erro",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {

                int i = 0;
                con.Open();
                MySqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select EMAIL from conta where EMAIL = @email  and LOGIN = @login ";
                cmd.Parameters.AddWithValue("@email", textBox2.Text);
                cmd.Parameters.AddWithValue("@login", textBox1.Text);
                cmd.ExecuteNonQuery();
                DataTable dt = new DataTable();
                MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                da.Fill(dt);
                i = Convert.ToInt32(dt.Rows.Count.ToString());

                if (i == 0)
                {
                    MessageBox.Show("Login ou email inválidos", "Erro",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    cmd.CommandText = "select * from CONTA where LOGIN = @login";
                    cmd.ExecuteNonQuery();

                    string senha = "";
                    string email = "";

                    MySqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        senha = reader.GetString("SENHA");
                        email = reader.GetString("EMAIL");
                    }

                    reader.Close();

                    using (SmtpClient smtp = new SmtpClient())
                    {
                        smtp.Host = "outlook.com";
                        smtp.UseDefaultCredentials = false;
                        NetworkCredential netCred = new NetworkCredential("email", "senha");
                        smtp.Credentials = netCred;
                        smtp.EnableSsl = true;

                        using (MailMessage msg = new MailMessage("email", email))
                        {
                            msg.Subject = "Recuperação de senha.";
                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine("A sua senha é atual é: " + senha  + Environment.NewLine);
                            sb.AppendLine("Obrigado," + Environment.NewLine);
                            sb.AppendLine("Digital wallet. " + Environment.NewLine);
                            msg.Body = sb.ToString();
                            msg.IsBodyHtml = false;
                            smtp.Send(msg);
                        }
                    }
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (!backgroundWorker1.IsBusy)
            {
                _inputparameter.Delay = 100;
                _inputparameter.Process = 1200;
                backgroundWorker1.RunWorkerAsync(_inputparameter);
             }
         }

        private void button2_Click(object sender, EventArgs e)
        {
          if (!backgroundWorker1.IsBusy)
        {
                backgroundWorker1.CancelAsync();
        }
           this.Close();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int process = ((DataParameter)e.Argument).Process;
            int delay = ((DataParameter)e.Argument).Delay;
            int index = 1;
            try
            {
                for (int i = 0; i < process; i++)
                {
                    if (!backgroundWorker1.CancellationPending)
                    {
                        backgroundWorker1.ReportProgress(index++ * 100 / process, string.Format("Process Data {0}", i));
                        SendEmail();
                    }
                }
            }
            catch(Exception ex)
            {
                backgroundWorker1.CancelAsync();
                MessageBox.Show(ex.Message, "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label3.Text = string.Format("Processando...{0}%", e.ProgressPercentage);
            progressBar1.Update();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("Email enviado.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
    
asked by anonymous 16.09.2017 / 22:47

1 answer

0

The problem may be regarding the configuration of your SmtpClient, you may need to set the sending mode and the port for SSL. I use the following method for sending email

 string _sender;
 string _password;
 public void SendMail(string destino, string subject, string message)
 {
     SmtpClient smtp = new SmtpClient("smtp-mail.outlook.com");

     smtp.Port = 587;
     smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
     smtp.UseDefaultCredentials = false;
     System.Net.NetworkCredential credentials =
     new System.Net.NetworkCredential(_sender, _password);
     smtp.EnableSsl = true;
     smtp.Credentials = credentials;

     try
     {
       var mail = new MailMessage(_sender.Trim(), destino.Trim());
       mail.Subject = subject;
       mail.Body = message;
       smtp.Send(mail);
     }
     catch (Exception ex)
     {
       Console.WriteLine(ex.Message);
       throw ex;
     }
   }

It is also necessary to enable the sending of e-mail, in the e-mail referring to the sending itself

    
18.09.2017 / 00:48