2012-07-28 17 views
12

E 'possibile inviare e-mail dal mio computer (localhost) usando il progetto asp.net in C#? Finalmente ho intenzione di caricare il mio progetto in webserver ma voglio testarlo prima del caricamento.invia email asp.net C#

Ho trovato i codici sorgente pronti e ho provato a eseguirli in localhost, ma nessuno dei due funziona con successo. Per esempio questo codice:

Così come per inviare e-mail utilizzando asp.net C#? Devo configurare alcune configurazioni del server?

+0

è possibile inviare e-mail utilizzando gmail, hotmail ecc. –

+0

mostraci il tuo codice. –

+0

Io uso questo http://smtp4dev.codeplex.com/ –

risposta

11

Invio E-mail da 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

Grazie, funziona! Ma cosa fare se non voglio usare gmail o hotmail. Voglio utilizzare il servizio di alcune società, ad esempio www.mycompany.com. Ho bisogno di qualche configurazione del server? È sufficiente conoscere l'host e il porto smtp? – Nurlan

+2

@NurlanKenzhebekov Non uso mai alcun servizio. L'invio di un'e-mail è un processo semplice. Se si utilizza qualsiasi servizio, la società fornisce domini di posta elettronica, penso che si debba usare solo smtp per inviare e-mail, non è richiesta alcuna configrazione del server. –

7

se si dispone di un account Gmail è possibile utilizzare Google SMTP per inviare una e-mail

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

Grazie, funziona! Ma cosa fare se non voglio usare gmail o hotmail. Voglio utilizzare il servizio di alcune società, ad esempio www.mycompany.com. Ho bisogno di qualche configurazione del server? È sufficiente conoscere l'host e il porto smtp? – Nurlan

2

È possibile inviare e-mail da ASP.NET tramite librerie di classe C# presenti nel System.Net.Mail namespace. dai un'occhiata alla classe SmtpClient che è la classe principale coinvolta nell'invio di e-mail.

È possibile trovare esempi di codice in Scott Gu's Blog o su MSDN page of SmtpClient.

Inoltre è necessario un server SMTP in esecuzione. Posso consigliare di utilizzare il server di posta SMTP4Dev che si rivolge allo sviluppo e non richiede alcuna configurazione.

+0

Grazie, funziona! Ma cosa fare se non voglio usare gmail o hotmail. Voglio utilizzare il servizio di alcune società, ad esempio www.mycompany.com. Ho bisogno di qualche configurazione del server? È sufficiente conoscere l'host e il porto smtp? – Nurlan

5

Il tuo codice di cui sopra dovrebbe funzionare bene, ma è necessario aggiungere quanto segue al vostro web.config (in alternativa a qualsiasi configurazione SMTP basato su codice):

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

Se non si ha accesso a un server SMTP remoto (io uso le mie informazioni e-mail POP3/SMTP), è possibile configurare un server SMTP nella tua istanza di IIS locale, ma si può incorrere in a problemi con l'inoltro (poiché la maggior parte degli indirizzi IP dei fornitori di servizi Internet sono elencati in nero).

Una buona alternativa, se non si ha accesso a un server SMTP, è quello di utilizzare le seguenti impostazioni al posto di quanto sopra:

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

Questo creerà una copia del disco rigido della posta elettronica, che è abbastanza utile. Dovrai creare la directory specificata sopra, altrimenti riceverai un messaggio di errore quando tenti di inviare email.

È possibile configurare questi dettagli nel codice come da altre risposte qui (configurando le proprietà sull'oggetto SmtpClient che è stato creato), ma a meno che non si ottengano le informazioni da un'origine dati o le informazioni siano dinamiche, è codifica superflua, quando .Net lo fa già per te.

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

Invia e-mail con allegato utilizzando asp.net 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); 

    } 

per passo tutorial completo dopo passo (con video) visita http://dotnetawesome.blogspot.in/2013/09/send-email-with-attachment-using-cnet.html

0

Di seguito è la soluzione per voi se non si desidera utilizzare 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); 

Spero che aiuti :)

0

Server.mappath non esiste. Non esiste un oggetto Server.