mercoledì 16 settembre 2009

Invio mail da GMail con ASP.NET 2.0

Nella creazione del mio ultimo GoogleGadget ho avuto dei problemi nell’invio di mail tramite Google.

Dopo vari test e documentazione sfogliata sono arrivato a questa soluzione:

System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage("from@gmail.com", "to@domain.it", "Subject", "test test");
mailMessage.IsBodyHtml = true;

System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); smtpClient.Credentials = new System.Net.NetworkCredential("from@gmail.com", "password");
smtpClient.EnableSsl = true;

smtpClient.Send(mailMessage);

Spero vi sia servita.

Nota aggiuntiva del 21 ottobre 2009:

La configurazione dell’SmtpClient può anche essere spostata nel web.config. Tutto tranne l’”EnableSsl” … per ovviare al problema ho aggiunto nella sezione appSettings la voce “smtpEnableSsl”.

<appSettings>
  <add key="smtpEnableSsl" value="True"/>
<appSettings>
<system.net>
  <mailSettings>
    <smtp from="mittente">
      <network host="smtp.gmail.com" port="587" userName="username" password="password" />
    </smtp>
  </mailSettings>
</system.net>

Il codice risultante sarà:

System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage("from@gmail.com", "to@domain.it", "Subject", "test test");
mailMessage.IsBodyHtml = true; //Imposta il tipo di mail ad HTML anziche TextPlain

System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
smtpClient.EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["smtpEnableSsl"]);

smtpClient.Send(mailMessage);

Ciao

Nessun commento:

La fusione fredda: un nuovo modo per ottenere energia

 Ciao ragazzi! Oggi voglio parlarvi di una cosa davvero interessante: la fusione fredda . Potrebbe sembrare qualcosa di uscito da un film di...