2012-07-28 64 views
12

¿Es posible enviar correos electrónicos desde mi computadora (localhost) usando el proyecto asp.net en C#? Finalmente, voy a subir mi proyecto al servidor web, pero quiero probarlo antes de subirlo.enviar correo electrónico asp.net C#

He encontrado códigos fuente listos y he intentado ejecutarlos en localhost, pero ninguno de ellos funciona con éxito. Por ejemplo este código:

Entonces, ¿cómo enviar correo electrónico utilizando asp.net C#? ¿Debo configurar algunas configuraciones de servidor?

+0

puede enviar correos electrónicos usando gmail, hotmail, etc. –

+0

muéstranos tu código. –

+0

Utilizo este http://smtp4dev.codeplex.com/ –

Respuesta

11

enviar correo electrónico desde Asp.Net:

MailMessage objMail = new MailMessage("Sending From", "Sending To","Email Subject", "Email Body"); 
    NetworkCredential objNC = new NetworkCredential("Sender Email","Sender Password"); 
    SmtpClient objsmtp = new SmtpClient("smtp.live.com", 587); // for hotmail 
    objsmtp.EnableSsl = true; 
    objsmtp.Credentials = objNC; 
    objsmtp.Send(objMail); 
+0

¡Gracias, funciona! Pero qué hacer si no quiero usar gmail o hotmail. Quiero usar el servicio de alguna compañía, por ejemplo www.mycompany.com. ¿Necesito alguna configuración de servidor? ¿Es suficiente si conozco el host y el puerto smtp? – Nurlan

+2

@NurlanKenzhebekov Nunca uso ningún servicio. Enviar un correo electrónico es un proceso fácil. Si usa algún servicio, entonces la compañía proporciona dominios de correo electrónico, creo que solo tiene que usar smtp para enviar correos electrónicos, no se requiere dicha configuración de servidor. –

7

si usted tiene una cuenta de Gmail puede utilizar Google SMTP para enviar un correo electrónico

smtpClient.UseDefaultCredentials = false; 
smtpClient.Host = "smtp.gmail.com"; 
smtpClient.Port = 587; 
smtpClient.Credentials = new NetworkCredential(username,passwordd); 
smtpClient.EnableSsl = true; 
smtpClient.Send(mailMessage); 
+0

¡Gracias, funciona! Pero qué hacer si no quiero usar gmail o hotmail. Quiero usar el servicio de alguna compañía, por ejemplo www.mycompany.com. ¿Necesito alguna configuración de servidor? ¿Es suficiente si conozco el host y el puerto smtp? – Nurlan

2

Puede enviar correo electrónico desde ASP.NET a través de las bibliotecas de clases de C# que se encuentran en el espacio de nombres System.Net.Mail. Eche un vistazo a la clase SmtpClient que es la clase principal involucrada al enviar correos electrónicos.

Puede encontrar ejemplos de código in Scott Gu's Blog o en el MSDN page of SmtpClient.

Además, necesitará un servidor SMTP en ejecución. Puedo recomendar el uso del servidor de correo SMTP4Dev que se dirige al desarrollo y no requiere ninguna configuración.

+0

¡Gracias, funciona! Pero qué hacer si no quiero usar gmail o hotmail. Quiero usar el servicio de alguna compañía, por ejemplo www.mycompany.com. ¿Necesito alguna configuración de servidor? ¿Es suficiente si conozco el host y el puerto smtp? – Nurlan

5

Su código debería funcionar bien, pero hay que añadir lo siguiente a su web.config (como alternativa a cualquier configuración SMTP basada en el código):

<system.net> 
    <mailSettings> 
     <smtp deliveryMethod="Network"> 
     <network host="your.smtpserver.com" port="25" userName="smtpusername" password="smtppassword" /> 
     </smtp> 
    </mailSettings> 
    </system.net> 

Si usted no tiene acceso a un servidor SMTP remoto (yo uso mis propios detalles de correo electrónico POP3/SMTP), puede configurar un servidor SMTP en la instancia local de IIS, pero puede funcionar para problemas con la retransmisión (ya que la mayoría de las direcciones IP del consumidor ISP están en la lista negra).

Una buena alternativa, si usted no tiene acceso a un servidor SMTP, es utilizar la siguiente configuración en lugar de lo anterior:

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

Esto creará una copia de disco duro del correo electrónico, el cual es bastante útil. Tendrá que crear el directorio que especificó arriba, de lo contrario recibirá un error al intentar enviar un correo electrónico.

Puede configurar estos detalles en el código según otras respuestas aquí (configurando las propiedades en el objeto SmtpClient que ha creado), pero a menos que obtenga la información de una fuente de datos o la información sea dinámica, es codificación superflua, cuando .Net ya hace esto por usted.

1
Create class name SMTP.cs then 

using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Net.Mail; 
using System.Net.Mime; 
using System.Net; 



/// <summary> 
/// Summary description for SMTP 
/// </summary> 
public class SMTP 
{ 
    private SmtpClient smtp; 

    private static string _smtpIp; 
    public static string smtpIp 
    { 
     get 
     { 
      if (string.IsNullOrEmpty(_smtpIp)) 
       _smtpIp = System.Configuration.ConfigurationManager.AppSettings["smtpIp"]; 

      return _smtpIp; 

     } 
    } 


    public SMTP() 
    { 
     smtp = new SmtpClient(smtpIp); 
    } 

    public string Send(string From, string Alias, string To, string Subject, string Body, string Image) 
    { 
     try 
     { 
      MailMessage m = new MailMessage("\"" + Alias + "\" <" + From + ">", To); 
      m.Subject = Subject; 
      m.Priority = MailPriority.Normal; 

      AlternateView av1 = AlternateView.CreateAlternateViewFromString(Body, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html); 

      if (!string.IsNullOrEmpty(Image)) 
      { 
       string path = HttpContext.Current.Server.MapPath(Image); 
       LinkedResource logo = new LinkedResource(path, MediaTypeNames.Image.Gif); 
       logo.ContentId = "Logo"; 
       av1.LinkedResources.Add(logo); 
      } 

      m.AlternateViews.Add(av1); 
      m.IsBodyHtml = true; 

      smtp.Send(m); 
     } 
     catch (Exception e) 
     { 
      return e.Message; 
     } 

     return "sucsess"; 
    } 
} 

then 

on aspx page 

protected void lblSubmit_Click(object sender, EventArgs e) 
    { 
     //HttpContext.Current.Response.ContentType = "text/plain"; 
     //Guid guid = Guid.NewGuid(); 
     string EmailMessage = "<html>" + 
             "<head>" + 
              "<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">" + 
             "</head>" + 
             "<body style=\"text-align:left;direction:ltr;font-family:Arial;\" >" + 
             "<style>a{color:#0375b7;} a:hover, a:active {color: #FF7B0C;}</style>" + 
               "<img src=\"" width=\"190px\" height= \"103px\"/><br/><br/>" + 
               "<p>Name: " + nameID.Value + ",<br/><br/>" + 
               "<p>Email: " + EmailID.Value + ",<br/><br/>" + 
                "<p>Comments: " + commentsID.Text + "<br/><br/>" + 
              // "Welcome to the Test local updates service!<br/>Before we can begin sending you updates, we need you to verify your address by clicking on the link below.<br/>" + 
               //"<a href=\""></a><br/><br/>" + 

               //"We look forward to keeping you informed of the latest and greatest events happening in your area.<br/>" + 
               //"If you have any questions, bug reports, ideas, or just want to talk, please contact us at <br/><br/>" + 
               //"Enjoy! <br/>" + commentsID.Text + "<br/>" + 

               //"Test<br/><a href=\"">www.Test.com</a></p>" + 
             "</body>" + 
            "</html>"; 

     lblThank.Text = "Thank you for contact us."; 
     // string Body = commentsID.Text; 
     SMTP smtp = new SMTP(); 
     string FromEmail = System.Configuration.ConfigurationManager.AppSettings["FromEmail"]; 
     string mailReturn = smtp.Send(EmailID.Value, "", FromEmail, "Contact Us Email", EmailMessage, string.Empty); 
     //HttpContext.Current.Response.Write("true"); 
     nameID.Value = ""; 
     EmailID.Value = ""; 
     commentsID.Text = ""; 
    } 
0

Enviar correo electrónico con archivo adjunto usando asp.neta de C#

public void Send(string from, string to, string Message, string subject, string host, int port, string password) 
    { 
     MailMessage email = new MailMessage(); 
     email.From = new MailAddress(from); 
     email.Subject = subject; 
     email.Body = Message; 
     SmtpClient smtp = new SmtpClient(host, port); 
     smtp.UseDefaultCredentials = false; 
     NetworkCredential nc = new NetworkCredential(txtFrom.Text.Trim(), password); 
     smtp.Credentials = nc; 
     smtp.EnableSsl = true; 
     email.IsBodyHtml = true; 

     email.To.Add(to); 

     string fileName = ""; 
     if (FileUpload1.PostedFile != null) 
     { 
      HttpPostedFile attchment = FileUpload1.PostedFile; 
      int FileLength = attchment.ContentLength; 
      if (FileLength > 0) 
      { 
       fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); 
       FileUpload1.PostedFile.SaveAs(Path.Combine(Server.MapPath("~/EmailAttachment"), fileName)); 
       Attachment attachment = new Attachment(Path.Combine(Server.MapPath("~/EmailAttachment"), fileName)); 
       email.Attachments.Add(attachment); 
      }    
     } 
     smtp.Send(email); 

    } 

para el paso completo tutorial a paso (con vídeo) visitan http://dotnetawesome.blogspot.in/2013/09/send-email-with-attachment-using-cnet.html

0

A continuación se muestra la solución para usted si usted no desea utilizar Gmail o Hotmail:

SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25); 

smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "myIDPassword"); 
smtpClient.UseDefaultCredentials = true; 
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; 
smtpClient.EnableSsl = true; 
MailMessage mail = new MailMessage(); 


//Setting From , To and CC 
mail.From = new MailAddress("[email protected]", "MyWeb Site"); 
mail.To.Add(new MailAddress("[email protected]")); 
mail.CC.Add(new MailAddress("[email protected]")); 


smtpClient.Send(mail); 

Espero que ayude :)

0

Server.mappath no existe. No hay un objeto Servidor

Cuestiones relacionadas