sending email by smtp

Asked

Viewed 1,454 times

0

I made a class that has the following code to send an email:

try
        {
            WebMail.SmtpServer = "smtp-mail.outlook.com";
            WebMail.SmtpPort = 25;
            WebMail.EnableSsl = true;
            WebMail.UserName = "meuemail";
            WebMail.Password = "minhasenha";
            WebMail.From = "[email protected]";

            WebMail.Send("[email protected]", "Notificação",
                Model.Nome + " é " + ((Model.VaiParticipar ?? false) ? "" : "Não") + "Sim");
        }
        catch (Exception)
        {
           @:<b>Desculpe, Email não enviado</b>
        }

Is there anything else missing? It’s always falling on catch, the email is not sent.

  • 2

    By chance this code stays on View? Why don’t you launch the exception to see the error message?

  • Desalex, when I used virtual/local IIS, running via debug/locally, never sent email (return message: Failed to connect server). I uploaded my application to the host, from there the email went perfectly. Via debug/locally I could never send. It may be some IIS trust, but I never checked.

  • the exception is this: System.Net.Webexception: Unable to connect to the remote server --> System.Net.Sockets.Socketexception: A connection attempt failed because the connected component did not respond correctly after a period of time or the established connection failed because the connected host did not respond

3 answers

6


You must change the port (Smtpport) from 25 to 587.

The Brazilian Internet Steering Committee (CGI.br) determined that as of January 1, 2013, all access providers and telephone companies no longer allow the sending of emails through port 25.

This means that all users who use email clients like Outlook, Windows Mail, Thunderbird or Apple mail among others should change their SMTP port from 25 to 587. This practice aims to reduce spam traffic in Brazil and consequently to improve the reputation of Brazilian Ips in CBL (blocking list that aggregates IP addresses that have been proven to send spam).

I suggest you read an interesting article about a simpler way to write your email submission class on http://www.omniscode.com.br/2015/11/19/cascade-lambda-pattern/

  • Thank you, it was the door

0

It tries to use this function ready that I use and does not give error, only if it is problem of its user.

    public class EmailServerAccount
    {
        public string EmailOrigem { get; set; }
        public string NomeOrigem { get; set; }
        public string Server { get; set; }
        public int Port { get; set; }
        public string User { get; set; }
        public string Pass { get; set; }
        public string Retorno { get; set; }
        public Boolean Autentica { get; set; }

    }

    public static string EnviarMensagem(EmailServerAccount conta, string[] destino, string[] emailcc, string mensagem, string titulo, string anexo)
    {
        string para = destino[0];

        if (String.IsNullOrEmpty(para)) 
        {
            return "Erro sem e-mail ! Assunto:" + titulo;
        }

        if (conta == null)
            return "Erro, conta de e-mail não existente !";

        MailMessage message = new MailMessage();
        message.From = new MailAddress(conta.EmailOrigem, conta.NomeOrigem);
        message.ReplyToList.Add(new MailAddress(conta.Retorno));

        string[] emaildestino = para.Split(';');
        //Destinatário
        foreach (string vEmailP in emaildestino)
        {
            message.To.Add(new MailAddress(vEmailP));
        }

        // message.To.Add(new MailAddress(""));

        //prioridade do email
        message.Priority = MailPriority.Normal;

        //utilize true pra ativar html no conteúdo do email, ou false, para somente texto
        message.IsBodyHtml = true;

        //Assunto do email
        message.Subject = titulo;

        //corpo do email a ser enviado
        message.Body = mensagem;

        // Envia a mensagem
        SmtpClient client = new SmtpClient(conta.Server, conta.Port);

        Boolean ssl = conta.Autentica;
        client.EnableSsl = ssl;

        // Insere as credenciais se o Servidor SMTP exigir
        ///  client.Credentials = CredentialCache.DefaultNetworkCredentials;

        //endereço do servidor SMTP(para mais detalhes leia abaixo do código)
        client.Host = conta.Server;

        //para envio de email autenticado, coloque login e senha de seu servidor de email
        //para detalhes leia abaixo do código
        client.Credentials = new NetworkCredential(conta.EmailOrigem, conta.Pass);

        try
        {
            client.Send(message);
            return "";
        }
        catch (Exception ex)
        {
            return " Erro no envio de email para !  " + para + "\r\n" + " " + ex.Message + "      -       " + ex.StackTrace + System.Environment.NewLine;
        }
    }

0

Change your source to capture the error message and understand where the problem is according to the modification below, another thing, check the port and ssl configuration, because for what I have used, there are rarely output servers using port 25 nowadays:

    }
    catch (Exception **erro**)
    {
       @:<b>Desculpe, Email não enviado</b> @:erro.Message
    }
  • If I pass error.Message it only returns me Failed to send email, if I pass only error then returns me error:System.Net.Webexception: Impossible to connect to remote server ---> System.Net.Sockets.Exception sockets: A connection attempt failed because the connected component did not respond correctly after a period of time or the established connection failed because the connected host did not respond

Browser other questions tagged

You are not signed in. Login or sign up in order to post.