private void okButton_Click(object sender, RoutedEventArgs e)
        {
            string host = serverBox.Text;
            int    port;
            string domain   = domainBox.Text;
            string email    = emailBox.Text;
            string password = passwordBox.Password;

            if (string.IsNullOrWhiteSpace(host) ||
                string.IsNullOrWhiteSpace(email) ||
                string.IsNullOrWhiteSpace(password) ||
                string.IsNullOrWhiteSpace(domain) ||
                !int.TryParse(portBox.Text, out port))
            {
                MessageBox.Show("You must fill in all fields", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            try
            {
                var server = new MailServer(host, port, domain);
                _client = new SmtpClient(new FileLogger(LogFile, true));
                _client.Connect(server);
                _client.Credentials = new Credentials(email, password, Encoding.UTF8);
                var mailWindow = new MainWindow(_client);
                mailWindow.Show();
                this.Close();
            }
            catch (AuthenticationFailedException ex)
            {
                _client?.Dispose();
                DetailedMessageBox.Show(this, ex.Message, "Log in error", ex.FullResponse, MessageBoxImage.Error);
                return;
            }
            catch (SmtpException ex)
            {
                _client?.Dispose();
                DetailedMessageBox.Show(this, ex.Message, "Smtp error", ex.FullResponse, MessageBoxImage.Error);
                return;
            }
            catch (FormatException)
            {
                _client?.Dispose();
                MessageBox.Show("Invalid email format!", "Email format error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            catch (Exception ex)
            {
                _client?.Dispose();
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }
Example #2
0
        public override bool Send(IMessageMail message)
        {
            SmtpClient  smtpClient = null;
            MailMessage mail       = null;

            try
            {
                if (!IsValidMessage(message))
                {
                    throw new ArgumentException("Message is invalid", nameof(message));
                }

                //Create mail message
                mail = CreateMessage(message);
                //Send message
                smtpClient = GetSmtpClient();
                smtpClient.Send(mail);

                return(true);
            }
            finally
            {
                mail?.Dispose();
                smtpClient?.Dispose();
            }
        }
Example #3
0
        private static SmtpClient CreateSmtpClient()
        {
            string host     = SDK.GetConfigValue("Smtp.Host");
            int?   port     = AH.ParseInt(SDK.GetConfigValue("Smtp.Port"));
            bool?  ssl      = bool.TryParse(SDK.GetConfigValue("Smtp.SslEnabled"), out bool s) ? s : (bool?)null;
            string username = SDK.GetConfigValue("Smtp.UserName");
            string password = SDK.GetConfigValue("Smtp.Password");

            if (string.IsNullOrEmpty(host) || port == null || ssl == null)
            {
                return(null);
            }

            SmtpClient client = null;

            try
            {
                client                       = new SmtpClient(host, port.Value);
                client.EnableSsl             = ssl.Value;
                client.UseDefaultCredentials = false; // login to mail server anonymously if no username/password specified

                if (!string.IsNullOrEmpty(username))
                {
                    client.Credentials = new NetworkCredential(username, password);
                }

                return(client);
            }
            catch
            {
                client?.Dispose();
                return(null);
            }
        }
Example #4
0
        internal static bool Send(string subject,
                                  string body,
                                  Settings settings)
        {
            var         result      = false;
            SmtpClient  smtpClient  = null;
            MailMessage mailMessage = null;

            try
            {
                smtpClient  = InitMailClientFromSettings(settings);
                mailMessage = CreateMail(subject, body, settings);
                smtpClient.Send(mailMessage);
                Log.Info = "Mail sent from " + settings.FromEmailAddress + " to " +
                           settings.ToEmailAddress;
                result = true;
            }
            catch (SmtpException ex)
            {
                Log.Error = ex;
            }
            catch (InvalidOperationException ex)
            {
                Log.Error = ex;
            }
            finally
            {
                mailMessage?.Dispose();
                smtpClient?.Dispose();
            }
            return(result);
        }
Example #5
0
        private static SmtpClient CreateSmtpClient(SmtpInfo smtpInfo, string host, int?port)
        {
            SmtpClient client = null;

            try
            {
                client      = new SmtpClient();
                client.Host = host;
                if (port != null)
                {
                    client.Port = port.Value;
                }

                SetSmtpClientAuthentication(smtpInfo, client);

                client.EnableSsl = smtpInfo.EnableSSL;

                var returnedClient = client;
                client = null;

                return(returnedClient);
            }
            finally
            {
                client?.Dispose();
            }
        }
Example #6
0
 //完成寄信後的callback function
 static void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)
 {
     IsSending = false;
     attachment?.Dispose();
     smtpClient?.Dispose();
     message?.Attachments?.Dispose();
     message?.Dispose();
 }
 public void Dispose()
 {
     if (!_disposed)
     {
         _smtpClient?.Dispose();
         _disposed = true;
     }
 }
 protected virtual void Dispose(bool disposing)
 {
     if (_isDisposed == false)
     {
         if (disposing)
         {
             _smtpClient?.Dispose();
         }
     }
     _isDisposed = true;
 }
Example #9
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             smtpClient?.Dispose();
         }
         disposed = true;
     }
 }
Example #10
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _client?.Dispose();
                }

                disposedValue = true;
            }
        }
Example #11
0
    public static bool EmailAlert(string to_add, string from_add, string em_sub, string em_bd, string smtp_server = null, string sAttachment = null)
    {
        int i = 0;
        string[] sTempA = null;
        SmtpClient SmtpMail = new SmtpClient();
        MailMessage MailMsg = new MailMessage();

        sTempA = to_add.Split(',');

        try
        {
            for (i = 0; i < (sTempA.Length -1); i++)
            {
                MailMsg.To.Add(new MailAddress(sTempA[i]));
            }

            MailMsg.From = new MailAddress(from_add);
            MailMsg.Subject = em_sub.Trim();
            MailMsg.Body = em_bd.Trim() + Environment.NewLine;

            if (sAttachment != null)
            {
                Attachment MsgAttach = new Attachment(sAttachment);
                MailMsg.Attachments.Add(MsgAttach);

                if (smtp_sender == null)
                {
                    // default
                    SmtpMail.Host = "";
                }
                else
                {
                    SmtpMail.Host = smtp_sender;
                }
                SmtpMail.Send(MailMsg);
                MsgAttach.Dispose();
            }
            else
            {
                SmtpMail.Host = smtp_sender;
                SmtpMail.Send(MailMsg);
            }
            return true;
        }
        catch (Exception ex)
        {
            sTempA = null;
            SmtpMail.Dispose();
            MailMsg.Dispose();
            //Console.WriteLine(ex);
            return false;
        }
    }
Example #12
0
        /// <summary>
        ///     Performs application-defined tasks associated with freeing,
        ///     releasing, or resetting unmanaged resources.
        /// </summary>
        ///
        /// <param name="disposing">
        ///     true to release both managed and unmanaged resources; false to release only unmanaged
        ///     resources.
        /// </param>
        private void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                _message?.Dispose();
                _client?.Dispose();
            }
            _disposed = true;
        }
Example #13
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _smtpClient?.Dispose();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                _disposed = true;
            }
        }
Example #14
0
        protected virtual void Dispose(bool flag)
        {
            if (_disposed)
            {
                return;
            }

            _smtpClient?.Disconnect(true);
            _smtpClient?.Dispose();
            _disposed = true;

            if (flag)
            {
                GC.SuppressFinalize(this);
            }
        }
Example #15
0
        public static void SendMessage(string subject,
                                       string body,
                                       MailAddress[] toAddresses,
                                       string projectIdentifier,
                                       bool isHTML           = false,
                                       MailPriority priority = MailPriority.Normal)
        {
            MailMessage msg    = null;
            SmtpClient  clt    = null;
            var         sender = projectIdentifier + SenderName;

            try
            {
                msg = new MailMessage()
                {
                    From       = new MailAddress(SenderAddr, sender),
                    Subject    = subject,
                    Body       = body,
                    IsBodyHtml = isHTML,
                    Priority   = priority
                };
                if (!System.Diagnostics.Debugger.IsAttached)
                {
                    foreach (var address in toAddresses)
                    {
                        msg.To.Add(address);
                    }
                }
                else
                {
                    msg.Subject += " (debug)";

                    msg.To.Add(DebugSender);
                }
                clt = new SmtpClient(ServerName);
                clt.Send(msg);
            }
            catch (Exception ex)
            {
                Log.Event(ex);
            }
            finally
            {
                msg?.Dispose();
                clt?.Dispose();
            }
        }
Example #16
0
        public static async Task SendEmailAsync(string message, string from, string to, string orderNumber)
        {
            MailMessage message1 = new MailMessage(from, to);

            message1.From = new MailAddress(from);
            string     fileName1   = HttpContext.Current.Server.MapPath("~/content/images/logo.jpg");
            string     fileName2   = HttpContext.Current.Server.MapPath("~/content/images/facebook.png");
            string     fileName3   = HttpContext.Current.Server.MapPath("~/content/images/instagram.jpg");
            Attachment attachment1 = new Attachment(fileName1);
            Attachment attachment2 = new Attachment(fileName2);
            Attachment attachment3 = new Attachment(fileName3);

            attachment1.ContentId = "logo";
            attachment2.ContentId = "facebook";
            attachment3.ContentId = "instagram";
            message1.Body         = "<html><body><p align='center'><img src = 'cid:" + attachment1.ContentId + "' /></p><hr />" + message + "<hr/><a href = '" + Settings.FacebookConnect + "'><img style = 'width:30px;height:30px;' src = 'cid:" + attachment2.ContentId + "' /></a><a href = '" + Settings.InstagramConnect + "' ><img style = 'width:30px;height:30px;' src = 'cid:" + attachment3.ContentId + "' /></a ><br/><a href = '" + Settings.FacebookConnect + "' >Follow us on Facebook</a><br/><br/><a href = '" + Settings.InstagramConnect + "' >Follow us on Instagram</a></body></html>";
            message1.Attachments.Add(attachment1);
            message1.Attachments.Add(attachment2);
            message1.Attachments.Add(attachment3);
            SmtpClient client = new SmtpClient();

            try
            {
                int result;
                int.TryParse(Settings.Port, out result);
                client.Port                  = result;
                client.EnableSsl             = true;
                client.UseDefaultCredentials = false;
                client.Host                  = Settings.SMTPServer;
                client.Credentials           = (ICredentialsByHost) new NetworkCredential(Settings.UserId, Settings.Password);
                message1.Subject             = "Your CraveTheShake Order #" + orderNumber;
                message1.IsBodyHtml          = true;
                try
                {
                    await client.SendMailAsync(message1);
                }
                catch (Exception ex)
                {
                }
            }
            finally
            {
                client?.Dispose();
            }
            client = (SmtpClient)null;
        }
Example #17
0
    /// <summary>
    /// Метод освобождения ресурсов.
    /// </summary>
    /// <param name="disposing">Флаг, который определяет необходимость освобождения управляемых ресурсов.</param>
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposedValue)
        {
            if (disposing)
            {
                if (_client != null && _client.IsConnected)
                {
                    _client.Disconnect(true);
                }

                _client?.Dispose();
            }

            _disposedValue = true;
        }
    }
Example #18
0
        private void EnviarCorreo()
        {
            SmtpClient smtp = null;

            try
            {
                smtp = new SmtpClient()
                {
                    Host = txtServer.Text.Trim()
                };

                if (int.TryParse(txtPort.Text.Trim(), out int intPort))
                {
                    smtp.Port = intPort;
                }

                if (!chkAnonymous.Checked)
                {
                    smtp.Credentials = new NetworkCredential()
                    {
                        UserName = txtLogin.Text.Trim(),
                        Password = txtPass.Text.Trim()
                    };

                    smtp.EnableSsl = chkSSL.Checked;
                }

                var msg = new MailMessage(txtForm.Text, txtTo.Text.Trim(), "SMTP Tester", "Mail de prueba");

                smtp.Send(msg);

                MessageBox.Show("Parece que todo guay ;-)");
            }
            catch (Exception e)
            {
                log(e.Message);
                log(e.InnerException?.Message);
                MessageBox.Show("error:" + e.Message);
            }
            finally
            {
                smtp?.Dispose();
            }
        }
Example #19
0
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            try
            {
                if (disposing)
                {
                    _smtpClient?.Dispose();
                    GC.SuppressFinalize(this);
                }
            }
            finally
            {
                _disposed = true;
            }
        }
Example #20
0
        private static SmtpClient InitMailClientFromSettings(Settings settings)
        {
            SmtpClient smtpClient = null;

            try
            {
#pragma warning disable IDE0017 // Simplify object initialization
                // ReSharper disable once UseObjectOrCollectionInitializer
                smtpClient = new SmtpClient(settings.smtpServer);
#pragma warning restore IDE0017 // Simplify object initialization
                smtpClient.Port        = Convert.ToInt32(settings.smtpPort, CultureInfo.InvariantCulture);
                smtpClient.Credentials = new NetworkCredential(
                    settings.emailUserName,
                    settings.emailPassword);
                smtpClient.EnableSsl = settings.useSSL;
            }
            catch (Exception)
            {
                smtpClient?.Dispose();
                throw;
            }
            return(smtpClient);
        }
Example #21
0
        private SmtpClient CreateSmtpClient()
        {
            string host     = SDK.GetConfigValue("Smtp.Host");
            int    port     = AH.ParseInt(SDK.GetConfigValue("Smtp.Port")) ?? 25;
            bool   ssl      = bool.TryParse(AH.CoalesceString(SDK.GetConfigValue("Smtp.SslEnabled"), SDK.GetConfigValue("Smtp.EnableSSL")), out bool s) ? s : false;
            string username = SDK.GetConfigValue("Smtp.UserName");
            string password = SDK.GetConfigValue("Smtp.Password");

            if (string.IsNullOrEmpty(host))
            {
                this.LogError("SMTP host not specified. Please set the \"Smtp.Host\" value in Advanced Settings.");
                return(null);
            }

            SmtpClient client = null;

            try
            {
                client = new SmtpClient(host, port)
                {
                    EnableSsl             = ssl,
                    UseDefaultCredentials = false // login to mail server anonymously if no username/password specified
                };

                if (!string.IsNullOrEmpty(username))
                {
                    client.Credentials = new NetworkCredential(username, password);
                }

                return(client);
            }
            catch
            {
                client?.Dispose();
                throw;
            }
        }
Example #22
0
 public void Dispose()
 {
     SmtpClient?.Dispose();
 }
Example #23
0
 public void Dispose()
 {
     client?.Dispose();
     client = null;
 }
Example #24
0
        protected override bool Dispatch(IMessage message)
        {
            SmtpClient  mailer = null;
            MailMessage mail   = null;

            try
            {
                mailer = ConfigureMailClient();
                if (mailer == null)
                {
                    return(false);
                }

                mail = new MailMessage();

                if (!string.IsNullOrWhiteSpace(message.From))
                {
                    mail.From = new MailAddress(message.From, string.IsNullOrWhiteSpace(message.FromName) ? string.Empty : message.FromName);
                }

                message.ToAddress.ForEach(s => mail.To.Add(new MailAddress(s)));
                message.Cc.ForEach(s => mail.CC.Add(new MailAddress(s)));
                message.Bcc.ForEach(s => mail.Bcc.Add(new MailAddress(s)));
                if (!string.IsNullOrWhiteSpace(message.ReplyTo))
                {
                    mail.ReplyToList.Add(new MailAddress(message.ReplyTo));
                }
                mail.Subject = message.Subject;

                if (!string.IsNullOrEmpty(message.Text))
                {
                    var plainView = AlternateView.CreateAlternateViewFromString(message.Text, null, MediaTypeNames.Text.Plain);
                    mail.AlternateViews.Add(plainView);
                }

                if (!string.IsNullOrEmpty(message.Html))
                {
                    var htmlView = AlternateView.CreateAlternateViewFromString(message.Html, null, MediaTypeNames.Text.Html);
                    mail.AlternateViews.Add(htmlView);

                    // TODO: Do we want to add a "Sorry, this email is formatted with HTML" text
                }

                message.Attachments.ForEach(att => AddAttachment(mail, att));

                // Custom headers
                foreach (var pair in message.Headers)
                {
                    mail.Headers.Add(pair.Key, pair.Value);
                }

                // Do not add header if no bounceAddress
                if (!string.IsNullOrWhiteSpace(message.BounceAddress))
                {
                    mail.Headers.Add("Return-Path", message.BounceAddress);
                }

                // Ok, send it
                TrySend(mail, mailer);

                return(true);
            }
            finally
            {
                // Get rid of the attachments and mailer explicitly - ensure we've sent
                mailer?.Dispose();

                if (mail != null)
                {
                    foreach (var attachment in mail.Attachments)
                    {
                        attachment.Dispose();
                    }
                    mail.Dispose();
                }
            }
        }
        /// <inheritdoc />
        public void Send(string subject, string body)
        {
            if (string.IsNullOrWhiteSpace(_runtimeSettings.EmailSenderAddress))
            {
                _logger.Error($"Unable to send email because setting '{nameof(_runtimeSettings.EmailSenderAddress)}' is missing! -- subject = {subject} -- body = {body}");
                return;
            }

            if (string.IsNullOrWhiteSpace(_runtimeSettings.EmailRecipientAddress))
            {
                _logger.Error($"Unable to send email because setting '{nameof(_runtimeSettings.EmailRecipientAddress)}' is missing! -- subject = {subject} -- body = {body}");
                return;
            }

            SmtpClient  client = null;
            MailMessage mm     = null;

            try
            {
                Debug.WriteLine("Creating mail message");
                mm = new MailMessage
                {
                    BodyEncoding = Encoding.UTF8,
                    IsBodyHtml   = false,
                    From         = new MailAddress(_runtimeSettings.EmailSenderAddress, _runtimeSettings.EmailSenderName ?? _runtimeSettings.EmailSenderAddress),
                    Subject      = subject,
                    Body         = body
                };
                mm.To.Add(new MailAddress(_runtimeSettings.EmailRecipientAddress, _runtimeSettings.EmailRecipientName ?? _runtimeSettings.EmailRecipientAddress));

                Debug.WriteLine("Creating SMTP Client");
                client = new SmtpClient
                {
                    Host                  = _runtimeSettings.EmailSmtpServer,
                    Port                  = _runtimeSettings.EmailSmtpPort,
                    EnableSsl             = _runtimeSettings.EmailSmtpUseSsl,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(_runtimeSettings.EmailSmtpLogonName, _runtimeSettings.EmailSmtpLogonPassword),
                    Timeout               = 30000
                };

                if (_isEmailSendingAllowed)
                {
                    Debug.WriteLine("Sending message...");
                    client.Send(mm);
                }
                else
                {
                    _logger.Warn($"Did not send email because {nameof(_isEmailSendingAllowed)} was {_isEmailSendingAllowed}");
                }
            }
            catch (SmtpException smtpEx)
            {
                var message = $"{nameof(SmtpException)} trying to send SmtpClient message: {smtpEx}";
                if (smtpEx.InnerException != null)
                {
                    message += $" --- Inner Exception: {smtpEx.InnerException}";
                }
                _logger?.Error(message);
            }
            catch (Exception ex)
            {
                var message = $"General exception trying to send SmtpClient message: {ex}";
                if (ex.InnerException != null)
                {
                    message += $" --- Inner Exception: {ex.InnerException}";
                }
                _logger?.Error(message);
            }
            finally
            {
                client?.Dispose();
                mm?.Dispose();
            }
        }
Example #26
0
 public void Dispose()
 {
     _client?.Dispose();
 }
Example #27
0
 public void Cleanup()
 {
     client?.Dispose();
 }
 public void Dispose() =>
     smtpClient?.Dispose();
Example #29
0
    public static bool TextAlert(string body, string textAlert = null)
    {
        // If established:
        if (textAlert == null)
        {
            textAlert = "";  // Default
        }

        bool check = false;
        string smtp_sender = "";
        string from = "";
        SmtpClient smtpcl = new SmtpClient(smtp_sender);

        if (body.Count() > 140)
        {
            string b;
            int start = 0;
            float bodycount = (body.Count() / 140);
            if (((body.Count() % 140) != 0))
            {
                for (int i = 1; i <= (bodycount + 1); i++)
                {
                    if (i == (bodycount + 1))
                    {
                        b = body.Substring(start, (body.Count() - start));
                    }
                    else
                    {
                        b = body.Substring(start, 140);
                    }

                    try
                    {
                        smtpcl.Send(from, textAlert, "", b);
                        check = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Text alert failed.  Error: " + ex.ToString());
                    }
                    start = start + 140;
                }
            }
            else
            {
                for (int i = 1; i <= bodycount; i++)
                {
                    b = body.Substring(start, 140);
                    try
                    {
                        smtpcl.Send(from, textAlert, "", b);
                        check = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Text alert failed.  Error: " + ex.ToString());
                    }
                    start = start + 140;
                }
            }
        }
        else
        {
            try
            {
                smtpcl.Send(from, textAlert, "", body);
                check = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Text alert failed.  Error: " + ex.ToString());
            }
        }

        smtpcl.Dispose();
        return check;
    }
Example #30
0
 ///<summary>Throws exceptions. Attempts to physically send the message over the network wire. This is used from wherever email needs to be
 ///sent throughout the program. If a message must be encrypted, then encrypt it before calling this function. nameValueCollectionHeaders can
 ///be null.</summary>
 public static void WireEmailUnsecure(BasicEmailAddress address, BasicEmailMessage emailMessage, NameValueCollection nameValueCollectionHeaders,
                                      params AlternateView[] arrayAlternateViews)
 {
     //For now we only support OAuth for Gmail but this may change in the future.
     if (!address.AccessToken.IsNullOrEmpty() && address.SMTPserver == "smtp.gmail.com")
     {
         SendEmailOAuth(address, emailMessage);
     }
     else
     {
         bool isImplicitSsl = (address.ServerPort == 465);
         if (isImplicitSsl)                 //Microsoft CDO supports implicit SSL, System.Net.Mail.SmtpClient only supports explicit SSL.
         {
             var cdo = new Message();
             var cfg = cdo.Configuration;
             cfg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value       = address.SMTPserver;
             cfg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value   = address.ServerPort;
             cfg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value        = "2";           //sendusing: 1=pickup, 2=port, 3=using microsoft exchange
             cfg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = "1";           //0=anonymous,1=clear text auth,2=context (NTLM)
             cfg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value     = address.EmailUsername.Trim();
             cfg.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value     = address.EmailPassword;
             cfg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"].Value       = true;            //false was also tested and does not work
             if (nameValueCollectionHeaders != null)
             {
                 //How to add headers which do not have formal fields - https://msdn.microsoft.com/en-us/library/ms526317(v=exchg.10).aspx
                 string[] arrayHeaderKeys = nameValueCollectionHeaders.AllKeys;
                 for (int i = 0; i < arrayHeaderKeys.Length; i++)                     //Needed for Direct Acks to work.
                 {
                     string headerName  = arrayHeaderKeys[i];
                     string headerValue = nameValueCollectionHeaders[headerName];
                     cfg.Fields["urn:schemas:mailheader:" + headerName].Value = headerValue;
                 }
             }
             cfg.Fields.Update();
             cdo.From = emailMessage.FromAddress.Trim();
             if (!string.IsNullOrWhiteSpace(emailMessage.ToAddress))
             {
                 cdo.To = emailMessage.ToAddress.Trim();
             }
             if (!string.IsNullOrWhiteSpace(emailMessage.CcAddress))
             {
                 cdo.CC = emailMessage.CcAddress.Trim();
             }
             if (!string.IsNullOrWhiteSpace(emailMessage.BccAddress))
             {
                 cdo.BCC = emailMessage.BccAddress.Trim();
             }
             cdo.Subject = emailMessage.Subject;
             if (emailMessage.IsHtml)
             {
                 cdo.HTMLBody = emailMessage.HtmlBody;
                 if (!emailMessage.ListHtmlImages.IsNullOrEmpty())
                 {
                     foreach (string imagePath in emailMessage.ListHtmlImages)
                     {
                         var imgAttach = cdo.AddAttachment(imagePath);
                         imgAttach.Fields["urn:schemas:mailheader:content-id"].Value = HttpUtility.UrlEncode(Path.GetFileName(imagePath));
                         imgAttach.Fields.Update();
                     }
                 }
             }
             else
             {
                 cdo.TextBody = emailMessage.BodyText;
             }
             if (!emailMessage.ListAttachments.IsNullOrEmpty())
             {
                 foreach (Tuple <string, string> attachmentPath in emailMessage.ListAttachments)
                 {
                     var cdoatt = cdo.AddAttachment(attachmentPath.Item1);
                     //Use actual file name for this field.
                     cdoatt.Fields["urn:schemas:mailheader:content-id"].Value = Path.GetFileName(attachmentPath.Item1);
                     cdoatt.Fields.Update();
                 }
             }
             cdo.Send();
         }
         else                  //No SSL or explicit SSL on port 587
         {
             SmtpClient  client  = null;
             MailMessage message = null;
             try {
                 client = new SmtpClient(address.SMTPserver, address.ServerPort);
                 //The default credentials are not used by default, according to:
                 //http://msdn2.microsoft.com/en-us/library/system.net.mail.smtpclient.usedefaultcredentials.aspx
                 client.Credentials    = new NetworkCredential(address.EmailUsername.Trim(), address.EmailPassword);
                 client.DeliveryMethod = SmtpDeliveryMethod.Network;
                 client.EnableSsl      = address.UseSSL;
                 client.Timeout        = 180000;               //3 minutes
                 message = BasicEmailMessageToMailMessage(emailMessage, nameValueCollectionHeaders, arrayAlternateViews);
                 client.Send(message);
             }
             finally {
                 //Dispose of the client and messages here. For large customers, sending thousands of emails will start to fail until they restart the
                 //app. Freeing memory here can prevent OutOfMemoryExceptions.
                 client?.Dispose();
                 if (message != null)
                 {
                     if (message.Attachments != null)
                     {
                         message.Attachments.ForEach(x => x.Dispose());
                     }
                     message.Dispose();
                 }
             }
         }
     }
 }
Example #31
0
 public void Dispose()
 {
     _smtp?.Dispose();
     _smtp = null;
     _from = null;
 }
Example #32
0
 public void Dispose()
 {
     _client?.Dispose();
     _address = null;
 }