private static void sendEmailWithSmtpServer( SmtpServer smtpServer, EmailMessage message ) { // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email. var smtpClient = new System.Net.Mail.SmtpClient(); try { if( smtpServer != null ) { smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Host = smtpServer.Server; if( smtpServer.PortSpecified ) smtpClient.Port = smtpServer.Port; if( smtpServer.Credentials != null ) { smtpClient.Credentials = new System.Net.NetworkCredential( smtpServer.Credentials.UserName, smtpServer.Credentials.Password ); smtpClient.EnableSsl = true; } } else { smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory; var pickupFolderPath = EwlStatics.CombinePaths( ConfigurationStatics.RedStaplerFolderPath, "Outgoing Dev Mail" ); Directory.CreateDirectory( pickupFolderPath ); smtpClient.PickupDirectoryLocation = pickupFolderPath; } using( var m = new System.Net.Mail.MailMessage() ) { message.ConfigureMailMessage( m ); try { smtpClient.Send( m ); } catch( System.Net.Mail.SmtpException e ) { throw new EmailSendingException( "Failed to send an email message using an SMTP server.", e ); } } } finally { // Microsoft's own dispose method fails to work if Host is not specified, even though Host doesn't need to be specified for operation. if( !string.IsNullOrEmpty( smtpClient.Host ) ) smtpClient.Dispose(); } }
private static void sendEmailWithSendGrid( SendGrid sendGrid, EmailMessage message ) { // We want this method to use the SendGrid API (https://github.com/sendgrid/sendgrid-csharp), but as of 20 June 2014 it looks like the SendGrid Web API // does not support CC recipients! // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email. var smtpClient = new System.Net.Mail.SmtpClient( "smtp.sendgrid.net", 587 ); try { smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Credentials = new System.Net.NetworkCredential( sendGrid.UserName, sendGrid.Password ); using( var m = new System.Net.Mail.MailMessage() ) { message.ConfigureMailMessage( m ); try { smtpClient.Send( m ); } catch( System.Net.Mail.SmtpException e ) { throw new EmailSendingException( "Failed to send an email message using SendGrid.", e ); } } } finally { smtpClient.Dispose(); } }