2012-03-27 14 views
10

¿Hay algún ejemplo que pueda explicarme que envíe correos electrónicos desde mi servidor localhost? He escrito este ejemplo pero no funciona, el error es "Error al enviar el correo".Enviando correo electrónico en asp.net a través del servidor de host local

SmtpClient smtpClient = new SmtpClient(); 
     smtpClient.Host = "localhost"; 
     smtpClient.Port = 25; 
     smtpClient.EnableSsl = false; 
     smtpClient.Credentials = new NetworkCredential("[email protected]", "secret"); 
     smtpClient.Send("[email protected]", "[email protected]", "Let’s eat lunch!", "Lunch at the Steak House?");//here is the error 

y qué debo hacer en web.config?

+1

¿Tiene SMTP configurado en localhost? – Habib

+0

estás usando localhost y usando credenciales de yahoo, no creo que esto funcione – Habib

Respuesta

19

Aquí ya go :) localhost-with-aspnet-without-smtp-server

Déjeme por favor saber si funciona para usted la forma en que lo necesite.


El enlace anterior no funciona, por lo que mejoraré la respuesta.

Para propósitos de prueba podemos utilizar localhost como esto: How to Test Email Without Configure SMTP in ASP.NET

En caso de que el enlace se cae de nuevo, básicamente tenemos que modificar web.config como esto:

<system.net> 
    <mailSettings> 
     <smtp deliveryMethod="SpecifiedPickupDirectory"> 
     <specifiedPickupDirectory pickupDirectoryLocation="C:\Mails\"/> 
     </smtp> 
    </mailSettings> 
    </system.net> 

y C# código

MailMessage mailMessage = new MailMessage(); 
    MailAddress fromAddress = new MailAddress("[email protected]"); 
    mailMessage.From = fromAddress; 
    mailMessage.To.Add("[email protected]"); 
    mailMessage.Body = "This is Testing Email Without Configured SMTP Server"; 
    mailMessage.IsBodyHtml = true; 
    mailMessage.Subject = " Testing Email"; 
    SmtpClient smtpClient = new SmtpClient(); 
    smtpClient.Host = "localhost"; 
    smtpClient.Send(mailMessage); 

Esto generará un archivo en nuestro directorio deseado.

+0

Nota: El 'System.Web.Mail.MailMessage' ahora está en desuso. Puede usar 'System.Net.Mail.MailMessage'. – rst

2

Debe especificar la configuración de su servidor SMTP en web.config. Hay varios ejemplos en línea (por ejemplo this)

<system.net> 
    <mailSettings> 
     <smtp deliveryMethod="Network" from="[email protected]"> 
      <network host="smtp.mail.com" userName="[email protected]" password="pwd" port="25"/> 
     </smtp> 
    </mailSettings> 
</system.net> 

A continuación, puede utilizar la clase SmtpClient enviar:

SmtpClient smtpClient = new SmtpClient(); 
smtpClient.EnableSsl = true; 

MailMessage msg = new MailMessage(); 
msg.To.Add("[email protected]"); 
msg.Subject = "test"; 
msg.Body = "test body"; 

smtpClient.Send(msg); 
+0

No necesita ningún servidor SMTP adicional ...;) – walther

+0

Acepto si está instalado en localhost. ¿Qué pasa si estás usando un proveedor externo (por ejemplo, Rackspace)? – Strillo

2

aquí es la muestra:

public static void SendMailMessage(string from, string to, string bcc, string cc, string subject, string body) 
{ 
    // Instantiate a new instance of MailMessage 
    MailMessage mMailMessage = new MailMessage(); 

    // Set the sender address of the mail message 
    mMailMessage.From = new MailAddress(from); 
    // Set the recepient address of the mail message 
    mMailMessage.To.Add(new MailAddress(to)); 

    // Check if the bcc value is null or an empty string 
    if ((bcc != null) && (bcc != string.Empty)) 
    { 
     // Set the Bcc address of the mail message 
     mMailMessage.Bcc.Add(new MailAddress(bcc)); 
    }  // Check if the cc value is null or an empty value 
    if ((cc != null) && (cc != string.Empty)) 
    { 
     // Set the CC address of the mail message 
     mMailMessage.CC.Add(new MailAddress(cc)); 
    }  // Set the subject of the mail message 
    mMailMessage.Subject = subject; 
    // Set the body of the mail message 
    mMailMessage.Body = body; 

    // Set the format of the mail message body as HTML 
    mMailMessage.IsBodyHtml = true; 
    // Set the priority of the mail message to normal 
    mMailMessage.Priority = MailPriority.Normal; 

    // Instantiate a new instance of SmtpClient 
    SmtpClient mSmtpClient = new SmtpClient(); 
    // Send the mail message 
    mSmtpClient.Send(mMailMessage); 
} 

Y llamar a la función :

SendMailMessage("[email protected]", "[email protected]", "[email protected]", "[email protected]", "Sample Subject", "Sample body of text for mail message") 
+0

Recibí 'System.InvalidOperationException: el host SMTP no se especificó. – mattalxndr

1
bool ret = true; 

      try 
      { 
       string _smtpServer = ConfigurationSettings.AppSettings["appEmailHost"]; 

       Web.Mail.Mail mail = new Web.Mail.Mail(_smtpServer,   
     System.Web.Mail.MailFormat.Html, System.Web.Mail.MailPriority.Normal); 
       mail._From = [email protected]; 
       mail._To = [email protected]; 
       mail._Subject = subject; 

       mail._Body = body; 
       mail.SendMail(); 
       ret = true; 
      } 
      catch(Exception exp) 
      { 
       _GravaErro(exp); 
       ret = false; 
      } 

      return ret; 
Cuestiones relacionadas