erro no envio do correio para a excepção smtp?

StringBuilder emailMessage = new StringBuilder();
emailMessage.Append("Dear Payment Team ,");
emailMessage.Append("<br><br>Please find the Payment instruction");    

try
{
    MailMessage Msg = new MailMessage();
    // Sender e-mail address.
    Msg.From = new MailAddress("[email protected]");
    // Recipient e-mail address.
    Msg.To.Add("[email protected]");
    Msg.CC.Add("[email protected]");
    Msg.Subject = "Timesheet Payment Instruction updated";
    Msg.IsBodyHtml = true;
    Msg.Body = emailMessage.ToString();
    SmtpClient smtp = new SmtpClient();
    //smtp.EnableSsl = true;

    smtp.Host = ConfigurationManager.AppSettings["HostName"];
    smtp.Port = int.Parse(ConfigurationManager.AppSettings["PortNumber"]);
    smtp.Send(Msg);
    Msg = null;
    Page.RegisterStartupScript("UserMsg", "<script>alert('Mail has been sent successfully.')</script>");
}
catch (Exception ex)
{
    Console.WriteLine("{0} Exception caught.", ex);
}

adicionei este código na web.config

<appSettings>
    <add key="HostName"   value="The host name as given by my company" />
    <add key="PortNumber" value="25" />
</appSettings>

continuo a ter uma excepção, tentei mudar o número do porto como especificado, mas sem sucesso

Pormenor Das Excepções

  System.Net.Mail.SmtpException was caught
  Message=Failure sending mail.
  Source=System
  StackTrace:
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at PAYMENT_DTALinesfollowup.Sendbtn_Click(Object sender, EventArgs e) in d:\AFSS-TFS\AFSS\Code\ERPNET\PAYMENT\DTALinesfollowup.aspx.cs:line 488
  InnerException: System.Net.WebException
       Message=Unable to connect to the remote server
       Source=System
       StackTrace:
            at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
            at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
            at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
            at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
            at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
            at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
            at System.Net.Mail.SmtpClient.GetConnection()
            at System.Net.Mail.SmtpClient.Send(MailMessage message)
       InnerException: System.Net.Sockets.SocketException
            Message=A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 125.63.68.148:25
            Source=System
            ErrorCode=10060
            NativeErrorCode=10060
            StackTrace:
                 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
                 at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
            InnerException: 
Author: Michael, 2012-11-22

5 answers

Tem de dar o nome de Utilizador e a senha para o smtp.

Utilizar o código abaixo: -

    MailSettings.SMTPServer = Convert.ToString(ConfigurationManager.AppSettings["HostName"]);
    MailMessage Msg = new MailMessage();
    // Sender e-mail address.
    Msg.From = new MailAddress("[email protected]");
    // Recipient e-mail address.
    Msg.To.Add("[email protected]");
    Msg.CC.Add("[email protected]");
    Msg.Subject = "Timesheet Payment Instruction updated";
    Msg.IsBodyHtml = true;
    Msg.Body = emailMessage.ToString();
    NetworkCredential loginInfo = new NetworkCredential(Convert.ToString(ConfigurationManager.AppSettings["UserName"]), Convert.ToString(ConfigurationManager.AppSettings["Password"])); // password for connection smtp if u dont have have then pass blank

    SmtpClient smtp = new SmtpClient();
    smtp.UseDefaultCredentials = true;
    smtp.Credentials = loginInfo;
    //smtp.EnableSsl = true;
    //No need for port
    //smtp.Host = ConfigurationManager.AppSettings["HostName"];
    //smtp.Port = int.Parse(ConfigurationManager.AppSettings["PortNumber"]);
     smtp.Send(Msg);
 4
Author: Hiral, 2015-08-20 06:57:36

Primeiro, você não precisa ler manualmente os valores no seu .ficheiro de configuração. Você pode definir o System.Net a secção e o seu objecto SmtpClient Irão lê-los automaticamente:

<system.net>
    <mailSettings>
      <smtp from="Sender's display name &lt;[email protected]&gt;">
        <network host="mailserver.yourdomain.com" port="25" userName="smtp_server_username" password="secret" defaultCredentials="false" />
      </smtp>
    </mailSettings>
  </system.net>
Então, a partir do seu código, basta escrever:
        SmtpClient smtp = new SmtpClient();
        MailMessage mailMessage = new MailMessage();
        mailMessage.To.Add(new MailAddress("[email protected]", "Recipient Display Name"));
        mailMessage.Subject = "Some Subject";
        mailMessage.Body = "One gorgeous body";
        smtp.Send(mailMessage);
Voltando ao seu erro, parece que tem algum tipo de problema de rede.
 2
Author: Ben, 2012-11-22 08:47:41
Sugiro que seja a forma mais simples de enviar e - mails com excepção, usando o Elmah. Por favor, siga esta linha de orientação para a solução: https://www.stormconsultancy.co.uk/blog/development/tools-plugins/setup-email-alerts-from-elmah-when-exceptions-are-raised/
 0
Author: Anh Hoang, 2014-10-24 04:20:28
try
           {
               MailMessage mail = new MailMessage();
               //SmtpClient SmtpServer = new SmtpClient("smtp.google.com");
              SmtpClient SmtpServer = new SmtpClient(sServer);

              // SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com", 587);
               mail.From = new MailAddress(sFromEmailId);
               mail.To.Add(sToEmailId);
               mail.Subject = sSubject;
               mail.Body = sMessage;
               mail.IsBodyHtml = true;             
               HttpFileCollection hfc = Request.Files;
               for (int i = 0; i < hfc.Count; i++)
               {
                   HttpPostedFile hpf = hfc[i];
                   if (hpf.ContentLength > 0)
                   {
                       mail.Attachments.Add(new Attachment(fupload.PostedFile.InputStream, hpf.FileName));

                   }
               }
               SmtpServer.Port = 587;
               //SmtpServer.Host = "smtp.gmail.com";
               SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
               SmtpServer.UseDefaultCredentials = false;
               SmtpServer.Credentials = new System.Net.NetworkCredential(sFromEmailId, sPassword);
               SmtpServer.EnableSsl = true;
               SmtpServer.Send(mail);                
               ClientScript.RegisterStartupScript(this.GetType(), "Alert", "dim('Mail Sent Successfully..!');", true);
               mail.Dispose();
           }
           catch (Exception ex)
           {                
               ClientScript.RegisterStartupScript(this.GetType(), "Alert", "dim('Error in Sending Mail..!');", true);
           }
 0
Author: venkatesh, 2015-08-11 05:45:55

Outra razão para esta excepção pode ser o vírus anti instalado no seu sistema. Isto pode estar proibindo a aplicação para enviar e-mails. Basta olhar para fora para uma caixa de diálogo que está pedindo permissão para enviar e-mails através de uma aplicação em seu sistema.

 0
Author: the.net-learner, 2017-02-13 09:07:39