Estou tentando criar uma aplicação para enviar emails de "esqueci a senha" mas sem sucesso até agora postei aqui um problema em que a tela estava congelando e dava tempo excedido da aplicação, me indicaram usar background worker, portanto estou usando agora mas mesmo assim a aplicação continua a dar erro no limite de tempo excedido e não envia nada, nem mesmo a barra de progresso faz nada. OBS: Mudei os campos de senha e email da função de enviar email por motivos óbvios. Segue o código.
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);
}
}
}