CSharp:.Net Email
From Aino Wiki
Libreria standard .Net
Invio di e-mail mediante server SMTP.
Uso
Esempio reale
using NLog; using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Net.Mail; using System.Reflection; //...etc private static Logger m_logger = LogManager.GetCurrentClassLogger(); //...etc /// <summary> /// Invio di una e-mail usando la libreria standard di .Net. /// Esecuzione protetta ovvero se c'è un errore o scatta una eccezione non si interrompe ma /// restituisce in uscita il messaggio di errore. /// </summary> /// <param name="smtpSrv"></param> /// <param name="smtpPort"></param> /// <param name="isSSL"></param> /// <param name="isAnonymous"></param> /// <param name="smtpDomain"></param> /// <param name="senderAlias"></param> /// <param name="userEmail"></param> /// <param name="userPw"></param> /// <param name="toEmailCSV"></param> /// <param name="CCEmailCSV"></param> /// <param name="BCCEmailCSV"></param> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="attachFilePathCSV"></param> /// <param name="logVerboseLevel">0=(Default) Nessun log! 1=Solo Errori, 2=Errori e Waring, 3=Information, 4=Tutto!</param> /// <returns>Messaggio di errore</returns> public static string SendEmail(string smtpSrv, int smtpPort , bool isSSL, bool isAnonymous , string smtpDomain, string senderAlias , string userEmail, string userPw , string toEmailCSV, string CCEmailCSV, string BCCEmailCSV , string subject , string body , string attachFilePathCSV , int logVerboseLevel = 0) // 0=Nessun log! 1=Solo Errori, 2=Errori e Waring, 3=Information, 4=Tutto! { string strErrorMessage = string.Empty; string emailTo = string.Empty; string firstAttachFileNameFullPath = string.Empty; MailMessage email = new MailMessage(); try { #region Log if (logVerboseLevel >= 4) m_logger.Debug("Send e-mail with Dot NET Lib"); if (smtpPort <= 0) { if (logVerboseLevel >= 2) m_logger.Warn("No port nr supplied, setting 25 default."); smtpPort = 25; } #endregion #region Normalizzazione CSV toEmailCSV = toEmailCSV.Replace(',', ';'); string[] arrEmailToDest = toEmailCSV.Split(new char[] { ';' } , StringSplitOptions.RemoveEmptyEntries); CCEmailCSV = CCEmailCSV.Replace(',', ';'); string[] arrEmailCCDest = CCEmailCSV.Split(new char[] { ';' } , StringSplitOptions.RemoveEmptyEntries); BCCEmailCSV = BCCEmailCSV.Replace(',', ';'); string[] arrEmailBCCDest = BCCEmailCSV.Split(new char[] { ';' } , StringSplitOptions.RemoveEmptyEntries); //userPw = string.IsNullOrWhiteSpace(userPw) ? null : userPw; string[] arrAttachFilePath = attachFilePathCSV.Split(new char[] { ';' } , StringSplitOptions.RemoveEmptyEntries); #endregion SmtpClient client = new SmtpClient(); client.Port = smtpPort; client.Host = smtpSrv; client.EnableSsl = isSSL; //client.ClientCertificates //client.Timeout = timeout; //In milliseconds client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; if (!isAnonymous) { if (string.IsNullOrWhiteSpace(smtpDomain)) { client.Credentials = new System.Net.NetworkCredential(userEmail, userPw); } else { client.Credentials = new System.Net.NetworkCredential(userEmail, userPw, smtpDomain); } } #region Composizione Mitt. e Destinatari email.Sender = new MailAddress(userEmail, senderAlias); email.From = new MailAddress(userEmail, senderAlias); // Destinatari in TO foreach (string destEmail in arrEmailToDest) { email.To.Add(new MailAddress(destEmail, destEmail)); emailTo = destEmail; } // Destinatari in CC foreach (string destEmail in arrEmailCCDest) { email.CC.Add(new MailAddress(destEmail, destEmail)); } // Destinatari in BCC foreach (string destEmail in arrEmailBCCDest) { email.Bcc.Add(new MailAddress(destEmail, destEmail)); } #endregion email.Subject = subject; email.IsBodyHtml = false; email.Body = body ?? string.Empty; //email.BodyEncoding = UTF8Encoding.UTF8; email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; #region Composizione allegati if (arrAttachFilePath != null && arrAttachFilePath.Length > 0) { foreach (string fileNameFullPath in arrAttachFilePath) { Attachment fileAttach = new Attachment(fileNameFullPath); email.Attachments.Add(fileAttach); } firstAttachFileNameFullPath = arrAttachFilePath[0]; } #endregion #region Log e INVIO ! if (logVerboseLevel >= 4) m_logger.Debug("\r\n" + "\tServer: \"{0}\"\t\tPort: \"{1}\"\r\n" + "\tSMTP Domain: \"{2}\"\r\n" + "\tSender Alias: \"{3}\"\r\n" + "\tIsAnonymous: \"{4}\"\r\n" + "\tUserName: \"{5}\"\r\n" + "\tSSL?: \"{6}\"\r\n" + "\tTo: \"{7}\"\r\n" + "\tNr To: \"{8}\"\r\n" + "\tCC CSV: \"{9}\"\r\n" + "\tBCC CSV: \"{10}\"\r\n" + "\tAttachFileFullPath: \"{11}\"\r\n" + "\tSubject: \"{12}\"\r\n" + "\tBody: \"{13}\"\r\n" , client.Host, client.Port , smtpDomain, senderAlias , isAnonymous , userEmail , client.EnableSsl , emailTo, arrEmailToDest.Length, CCEmailCSV, BCCEmailCSV , firstAttachFileNameFullPath , subject , body ?? "<Empty>"); client.Send(email); //INVIO !!! if (logVerboseLevel >= 3) m_logger.Info("E-mail sent"); // Se ci son stati allegati occorre "staccarli" dall'oggetto 'client' per evitare che // successivamente non li si possa cancellare perché risultanti in uso ! if (email.Attachments != null) { for (int i = email.Attachments.Count - 1; i >= 0; i--) { email.Attachments[i].Dispose(); } email.Attachments.Clear(); email.Attachments.Dispose(); if (logVerboseLevel >= 4) m_logger.Info("Attachments disposed"); } #endregion email.Dispose(); email = null; } catch (Exception ex) { string fullError = ex.Message; if (logVerboseLevel >= 2) m_logger.Error(ex); Exception iEx = ex; while (iEx.InnerException != null && !string.IsNullOrWhiteSpace(iEx.InnerException.Message)) { fullError = string.Format("{0} {1}", fullError, iEx.InnerException.Message); iEx = iEx.InnerException; } strErrorMessage = string.Format("Error sending e-mail: '{0}'\r\nTo '{1}'" , fullError, toEmailCSV); } return strErrorMessage; }
Verifica server SMTP
public static bool? SMTP_Hello(string smtpSrv, int smtpPort, bool isSSL , out string srvSMTPResponse) { bool? srvUP = null; srvSMTPResponse = string.Empty; try { using (var client = new TcpClient()) { client.Connect(smtpSrv, smtpPort); // As GMail requires SSL we should use SslStream // If your SMTP server doesn't support SSL you can // work directly with the underlying stream if (isSSL) { using (var stream = client.GetStream()) using (var sslStream = new SslStream(stream)) { sslStream.AuthenticateAsClient(smtpSrv); using (var writer = new StreamWriter(sslStream)) using (var reader = new StreamReader(sslStream)) { writer.WriteLine("EHLO " + smtpSrv); writer.Flush(); srvSMTPResponse = reader.ReadLine(); m_logger.Info(srvSMTPResponse); //Console.WriteLine(reader.ReadLine()); // GMail responds with: 220 mx.google.com ESMTP } } } else { using (var stream = client.GetStream()) using (var writer = new StreamWriter(stream)) using (var reader = new StreamReader(stream)) { writer.WriteLine("EHLO " + smtpSrv); writer.Flush(); srvSMTPResponse = reader.ReadLine(); m_logger.Info(srvSMTPResponse); } } } srvUP = true; } catch (Exception ex) { srvUP = false; srvSMTPResponse = ex.Message; m_logger.Error(ex.Message); } return srvUP; }
Mappa e Link
Visual Studio | MS SQL | Dizionario
Parole chiave: