Send Email to my account c #

-1

In creating my program, I put a Form so that you can use it to "Report Error / Suggestions". In this form I put 2 textbox and 1 button . 1 textbox to Subject , and the other to write what you want (message). The button serves to send this data to my email. The code I have is the following:

    if (!(txtpara.Text.Trim() == ""))
        {
            To = txtpara.Text;
            Subject = txtassunto.Text;
            Body = txtmensagem.Text;

            mail = new MailMessage();
            mail.To.Add(new MailAddress(this.To));
            mail.From = new MailAddress("[email protected]");
            mail.Subject = Subject;
            mail.Body = Body;
            mail.IsBodyHtml = false;

            SmtpClient client = new SmtpClient("smtp.gmail.com", 465);
            using (client)
            {
                client.Credentials = new System.Net.NetworkCredential("[email protected]", "aminhapassword");
                client.EnableSsl = true;
                client.Send(mail);
            }
            MessageBox.Show("E-Mail enviado com Sucesso!", "Sucesso");
        }

The error is in:

  

"client.Send (mail);" and says "Failed to send email" - SmtpException.

    
asked by anonymous 11.04.2015 / 03:55

1 answer

3

Probably the SMTP port you are using is incorrect, I know you can use 25, 465, and 587, but I only succeeded using 587.

System.Net.Mail.SmtpClient Smtp = new SmtpClient();
Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
Smtp.UseDefaultCredentials = false;
Smtp.Timeout = 300000;
Smtp.Host = "smtp.gmail.com";
Smtp.Port = 587;
Smtp.EnableSsl = true;
Smtp.Credentials = new System.Net.NetworkCredential("xxx", "xxx");
Smtp.Send(Mensagem);

This is a code running in production for sending e-mail using a gmail account.

@Edit for comments: To capture the Exception text, add this line instead of the last:

try{
    Smtp.Send(Mensagem);
} catch( Exception ex) { 
    string s = ex.ToString(); //Tratar a exceção
}

Remembering that this try / catch implementation is only for receiving data from your exception, it is not recommended to handle exceptions that way.

    
13.04.2015 / 14:10