1

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);
        }
    }
}

1 Resposta 1

0

O problema pode ser referente a configuração do seu SmtpClient, talvez seja necessário definir o modo de envio e a porta para SSL. Utilizo o seguinte método para envio de e-mail

 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;
     }
   }

Também é necessário habilitar o envio de e-mail, no próprio e-mail referente ao envio

2
  • Sim era exatamente a porta. 17/09/2017 às 23:56
  • Aceite a resposta caso tenha dado certo :) 18/09/2017 às 14:08

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .