/// <summary>
        /// Applies the override to a MailAddressCollection
        /// </summary>
        /// <param name="addresses">The addresses.</param>
        /// <returns></returns>
        protected MailAddressCollection ApplyMailAddressOverride(MailAddressCollection addresses)
        {
            if (clear)
            {
                addresses.Clear();
            }
            else
            {
                if (!string.IsNullOrEmpty(overrideString))
                {
                    addresses.Clear();
                    addresses.Add(overrideString);
                }

                if (!string.IsNullOrEmpty(prependString))
                {
                    var old = addresses.ToString();
                    addresses.Clear();
                    addresses.Add(prependString);
                    if (!string.IsNullOrWhiteSpace(old))
                    {
                        addresses.Add(old);
                    }
                }

                if (!string.IsNullOrEmpty(appendString))
                {
                    addresses.Add(appendString);
                }
            }

            return(addresses);
        }
        /// <summary>
        /// Applies the override to a MailAddressCollection
        /// </summary>
        /// <param name="addresses">The addresses.</param>
        /// <returns></returns>
        protected MailAddressCollection ApplyMailAddressOverride(MailAddressCollection addresses)
        {
            if (clear)
            {
                addresses.Clear();
            }
            else
            {
                if (!string.IsNullOrEmpty(overrideString))
                {
                    addresses.Clear();
                    addresses.Add(overrideString);
                }

                if (!string.IsNullOrEmpty(prependString))
                {
                    var old = addresses.ToString();
                    addresses.Clear();
                    addresses.Add(prependString);
                    if(!string.IsNullOrWhiteSpace(old)) addresses.Add(old);
                }

                if (!string.IsNullOrEmpty(appendString))
                {
                    addresses.Add(appendString);
                }
            }

            return addresses;
        }
Esempio n. 3
0
 private static void SetAddressesToCollection(MailAddressCollection addressCollection, string emailsText)
 {
     addressCollection.Clear();
     if (!string.IsNullOrEmpty(emailsText))
     {
         string[] emails = emailsText.Split(EmailsSeparators, StringSplitOptions.RemoveEmptyEntries);
         for (int i = 0; i < emails.Length; i++)
         {
             addressCollection.Add(emails[i]);
         }
     }
 }
Esempio n. 4
0
        /*******************************************************************************************************************************/
        /* Elshiekh Code */
        /*******************************************************************************************************************************/
        //------------------------------------------
        //Get mail address collection from string
        //------------------------------------------

        public static void GetMailAddressCollectionFromCollectionString(string adressesString, MailAddressCollection collection)
        {
            if (!string.IsNullOrEmpty(adressesString))
            {
                string[] addressesAray = adressesString.Split(new Char[] { ',' });
                //clear previous list
                collection.Clear();
                //add new items
                for (int i = 0; i < addressesAray.Length; i++)
                {
                    collection.Add(addressesAray[i]);
                }
            }
            //return collection;
        }
Esempio n. 5
0
 /// <summary>
 /// Clears any recipients assigned to the BCC list.
 /// </summary>
 public void ClearBCCs()
 {
     bccs.Clear();
 }
Esempio n. 6
0
 /// <summary>
 /// Clears any recipients assigned to the CC list.
 /// </summary>
 public void ClearCCs()
 {
     ccs.Clear();
 }
Esempio n. 7
0
 /// <summary>
 /// Clears any recipients assigned to the To list.
 /// </summary>
 public void ClearRecipients()
 {
     recipients.Clear();
 }
Esempio n. 8
0
        /// <summary>
        /// This method takes the input from the form, creates a mail message and sends it to the smtp server
        /// </summary>
        private void SendEmail()
        {
            // make sure we have values in user, password and To
            if (ValidateForm() == false)
            {
                return;
            }

            // create mail, smtp and mailaddress objects
            MailMessage mail = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            MailAddressCollection mailAddrCol = new MailAddressCollection();

            try
            {
                // set the From email address information
                mail.From = new MailAddress(txtBoxEmailAddress.Text);

                // set the To email address information
                mailAddrCol.Clear();
                _logger.Log("Adding To addresses: " + txtBoxTo.Text);
                mailAddrCol.Add(txtBoxTo.Text);
                MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.To);

                // check for Cc and Bcc, which can be empty so we only need to add when the textbox contains a value
                if (txtBoxCC.Text.Trim() != "")
                {
                    mailAddrCol.Clear();
                    _logger.Log("Adding Cc addresses: " + txtBoxCC.Text);
                    mailAddrCol.Add(txtBoxCC.Text);
                    MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.Cc);
                }

                if (txtBoxBCC.Text.Trim() != "")
                {
                    mailAddrCol.Clear();
                    _logger.Log("Adding Bcc addresses: " + txtBoxBCC.Text);
                    mailAddrCol.Add(txtBoxBCC.Text);
                    MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.Bcc);
                }

                // set encoding for message
                if (Properties.Settings.Default.BodyEncoding != "")
                {
                    mail.BodyEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.BodyEncoding);
                }
                if (Properties.Settings.Default.SubjectEncoding != "")
                {
                    mail.SubjectEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.SubjectEncoding);
                }
                if (Properties.Settings.Default.HeaderEncoding != "")
                {
                    mail.HeadersEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.HeaderEncoding);
                }

                // set priority for the message
                switch (Properties.Settings.Default.MsgPriority)
                {
                    case "High":
                        mail.Priority = MailPriority.High;
                        break;
                    case "Low":
                        mail.Priority = MailPriority.Low;
                        break;
                    default:
                        mail.Priority = MailPriority.Normal;
                        break;
                }

                // add HTML AltView
                if (Properties.Settings.Default.AltViewHtml != "")
                {
                    ContentType ctHtml = new ContentType("text/html");
                    htmlView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewHtml, ctHtml);

                    // add inline attachments / linked resource
                    if (inlineAttachmentsTable.Rows.Count > 0)
                    {
                        foreach (DataRow rowInl in inlineAttachmentsTable.Rows)
                        {
                            LinkedResource lr = new LinkedResource(rowInl.ItemArray[0].ToString());
                            lr.ContentId = rowInl.ItemArray[1].ToString();
                            lr.ContentType.MediaType = rowInl.ItemArray[2].ToString();
                            htmlView.LinkedResources.Add(lr);
                            lr.Dispose();
                        }
                    }

                    // set transfer encoding
                    htmlView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.htmlBodyTransferEncoding);
                    mail.AlternateViews.Add(htmlView);
                }

                // add Plain Text AltView
                if (Properties.Settings.Default.AltViewPlain != "")
                {
                    ContentType ctPlain = new ContentType("text/plain");
                    plainView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewPlain, ctPlain);
                    plainView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.plainBodyTransferEncoding);
                    mail.AlternateViews.Add(plainView);
                }

                // add vCal AltView
                if (Properties.Settings.Default.AltViewCal != "")
                {
                    ContentType ctCal = new ContentType("text/calendar");
                    ctCal.Parameters.Add("method", "REQUEST");
                    ctCal.Parameters.Add("name", "meeting.ics");
                    calView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewCal, ctCal);
                    calView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.vCalBodyTransferEncoding);
                    mail.AlternateViews.Add(calView);
                }

                // add custom headers
                foreach (DataGridViewRow rowHdr in dGridHeaders.Rows)
                {
                    if (rowHdr.Cells[0].Value != null)
                    {
                        mail.Headers.Add(rowHdr.Cells[0].Value.ToString(), rowHdr.Cells[1].Value.ToString());
                    }
                }

                // add attachements
                foreach (DataGridViewRow rowAtt in dGridAttachments.Rows)
                {
                    if (rowAtt.Cells[0].Value != null)
                    {
                        Attachment data = new Attachment(rowAtt.Cells[0].Value.ToString(), FileUtilities.GetContentType(rowAtt.Cells[1].Value.ToString()));
                        if (rowAtt.Cells[4].Value.ToString() == "True")
                        {
                            data.ContentDisposition.Inline = true;
                            data.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                            data.ContentId = rowAtt.Cells[3].Value.ToString();
                            Properties.Settings.Default.BodyHtml = true;
                        }
                        else
                        {
                            data.ContentDisposition.Inline = false;
                            data.ContentDisposition.DispositionType = DispositionTypeNames.Attachment;
                        }
                        mail.Attachments.Add(data);
                        data.Dispose();
                    }
                }

                // add read receipt
                if (Properties.Settings.Default.ReadRcpt == true)
                {
                    mail.Headers.Add("Disposition-Notification-To", txtBoxEmailAddress.Text);
                }

                // set the content
                mail.Subject = txtBoxSubject.Text;
                msgSubject = txtBoxSubject.Text;
                mail.Body = richTxtBody.Text;
                mail.IsBodyHtml = Properties.Settings.Default.BodyHtml;

                // add delivery notifications
                if (Properties.Settings.Default.DelNotifOnFailure == true)
                {
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                }

                if (Properties.Settings.Default.DelNotifOnSuccess == true)
                {
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                }

                // check for credentials
                string sUser = txtBoxEmailAddress.Text.Trim();
                string sPassword = mskPassword.Text.Trim();
                string sDomain = txtBoxDomain.Text.Trim();

                if (sUser.Length != 0)
                {
                    if (sDomain.Length != 0)
                    {
                        smtp.Credentials = new NetworkCredential(sUser, sPassword, sDomain);
                    }
                    else
                    {
                        smtp.Credentials = new NetworkCredential(sUser, sPassword);
                    }
                }

                // send by pickup folder?
                if (rdoSendByPickupFolder.Checked)
                {
                    if (this.chkBoxSpecificPickupFolder.Checked)
                    {
                        if (Directory.Exists(txtPickupFolder.Text))
                        {
                            smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                            smtp.PickupDirectoryLocation = txtPickupFolder.Text;
                        }
                        else
                        {
                            throw new DirectoryNotFoundException(@"The specified directory """ + txtPickupFolder.Text + @""" does not exist.");
                        }
                    }
                    else
                    {
                        smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                    }
                }

                // smtp client setup
                smtp.EnableSsl = chkEnableSSL.Checked;
                smtp.Port = Int32.Parse(cboPort.Text.Trim());
                smtp.Host = cboServer.Text;
                smtp.Timeout = Properties.Settings.Default.SendSyncTimeout;

                // send email
                smtp.Send(mail);
            }
            catch (SmtpException se)
            {
                txtBoxErrorLog.Clear();
                noErrFound = false;
                if (se.StatusCode == SmtpStatusCode.MailboxBusy || se.StatusCode == SmtpStatusCode.MailboxUnavailable)
                {
                    _logger.Log("Delivery failed - retrying in 5 seconds.");
                    System.Threading.Thread.Sleep(5000);
                    smtp.Send(mail);
                }
                else
                {
                    _logger.Log("Error: " + se.Message);
                    _logger.Log("StackTrace: " + se.StackTrace);
                    _logger.Log("Status Code: " + se.StatusCode);
                    _logger.Log("Description:" + MessageUtilities.GetSmtpStatusCodeDescription(se.StatusCode.ToString()));
                }
            }
            catch (InvalidOperationException ioe)
            {
                // invalid smtp address used
                txtBoxErrorLog.Clear();
                noErrFound = false;
                _logger.Log("Error: " + ioe.Message);
                _logger.Log("StackTrace: " + ioe.StackTrace);
            }
            catch (FormatException fe)
            {
                // invalid smtp address used
                txtBoxErrorLog.Clear();
                noErrFound = false;
                _logger.Log("Error: " + fe.Message);
                _logger.Log("StackTrace: " + fe.StackTrace);
            }
            catch (Exception ex)
            {
                txtBoxErrorLog.Clear();
                noErrFound = false;
                _logger.Log("Error: " + ex.Message);
                _logger.Log("StackTrace: " + ex.StackTrace);
            }
            finally
            {
                // log success
                if (formValidated == true && noErrFound == true)
                {
                    _logger.Log("Message subject = " + msgSubject);
                    _logger.Log("Message send = SUCCESS");
                }

                // cleanup resources
                mail.Dispose();
                mail = null;
                smtp.Dispose();
                smtp = null;

                // reset variables
                formValidated = false;
                noErrFound = true;
                inlineAttachmentsTable.Clear();
                hdrName = null;
                hdrValue = null;
                msgSubject = null;
            }
        }
Esempio n. 9
0
        /// <summary>
        /// This method takes the input from the form, creates a mail message and sends it to the smtp server
        /// </summary>
        private void SendEmail()
        {
            // make sure we have values in user, password and To
            if (ValidateForm() == false)
            {
                return;
            }

            // create mail, smtp and mailaddress objects
            MailMessage           mail        = new MailMessage();
            SmtpClient            smtp        = new SmtpClient();
            MailAddressCollection mailAddrCol = new MailAddressCollection();

            try
            {
                // set the From email address information
                mail.From = new MailAddress(txtBoxEmailAddress.Text);

                // set the To email address information
                mailAddrCol.Clear();
                logger.Log("Adding To addresses: " + txtBoxTo.Text);
                mailAddrCol.Add(txtBoxTo.Text);
                MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.To);

                // check for Cc and Bcc, which can be empty so we only need to add when the textbox contains a value
                if (txtBoxCC.Text.Trim() != "")
                {
                    mailAddrCol.Clear();
                    logger.Log("Adding Cc addresses: " + txtBoxCC.Text);
                    mailAddrCol.Add(txtBoxCC.Text);
                    MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.Cc);
                }

                if (txtBoxBCC.Text.Trim() != "")
                {
                    mailAddrCol.Clear();
                    logger.Log("Adding Bcc addresses: " + txtBoxBCC.Text);
                    mailAddrCol.Add(txtBoxBCC.Text);
                    MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.Bcc);
                }

                // set encoding for message
                if (Properties.Settings.Default.BodyEncoding != "")
                {
                    mail.BodyEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.BodyEncoding);
                }
                if (Properties.Settings.Default.SubjectEncoding != "")
                {
                    mail.SubjectEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.SubjectEncoding);
                }
                if (Properties.Settings.Default.HeaderEncoding != "")
                {
                    mail.HeadersEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.HeaderEncoding);
                }

                // set priority for the message
                switch (Properties.Settings.Default.MsgPriority)
                {
                case "High":
                    mail.Priority = MailPriority.High;
                    break;

                case "Low":
                    mail.Priority = MailPriority.Low;
                    break;

                default:
                    mail.Priority = MailPriority.Normal;
                    break;
                }

                // add HTML AltView
                if (Properties.Settings.Default.AltViewHtml != "")
                {
                    ContentType ctHtml = new ContentType("text/html");
                    htmlView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewHtml, ctHtml);

                    // add inline attachments / linked resource
                    if (inlineAttachmentsTable.Rows.Count > 0)
                    {
                        foreach (DataRow rowInl in inlineAttachmentsTable.Rows)
                        {
                            LinkedResource lr = new LinkedResource(rowInl.ItemArray[0].ToString());
                            lr.ContentId             = rowInl.ItemArray[1].ToString();
                            lr.ContentType.MediaType = rowInl.ItemArray[2].ToString();
                            htmlView.LinkedResources.Add(lr);
                            lr.Dispose();
                        }
                    }

                    // set transfer encoding
                    htmlView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.htmlBodyTransferEncoding);
                    mail.AlternateViews.Add(htmlView);
                }

                // add Plain Text AltView
                if (Properties.Settings.Default.AltViewPlain != "")
                {
                    ContentType ctPlain = new ContentType("text/plain");
                    plainView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewPlain, ctPlain);
                    plainView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.plainBodyTransferEncoding);
                    mail.AlternateViews.Add(plainView);
                }

                // add vCal AltView
                if (Properties.Settings.Default.AltViewCal != "")
                {
                    ContentType ctCal = new ContentType("text/calendar");
                    ctCal.Parameters.Add("method", "REQUEST");
                    ctCal.Parameters.Add("name", "meeting.ics");
                    calView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewCal, ctCal);
                    calView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.vCalBodyTransferEncoding);
                    mail.AlternateViews.Add(calView);
                }

                // add custom headers
                foreach (DataGridViewRow rowHdr in dgGridHeaders.Rows)
                {
                    if (rowHdr.Cells[0].Value != null)
                    {
                        mail.Headers.Add(rowHdr.Cells[0].Value.ToString(), rowHdr.Cells[1].Value.ToString());
                    }
                }

                // add attachements
                foreach (DataGridViewRow rowAtt in dgGridAttachments.Rows)
                {
                    if (rowAtt.Cells[0].Value != null)
                    {
                        Attachment data = new Attachment(rowAtt.Cells[0].Value.ToString(), FileUtilities.GetContentType(rowAtt.Cells[1].Value.ToString()));
                        if (rowAtt.Cells[4].Value.ToString() == "True")
                        {
                            data.ContentDisposition.Inline          = true;
                            data.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                            data.ContentId = rowAtt.Cells[3].Value.ToString();
                            Properties.Settings.Default.BodyHtml = true;
                        }
                        else
                        {
                            data.ContentDisposition.Inline          = false;
                            data.ContentDisposition.DispositionType = DispositionTypeNames.Attachment;
                        }
                        mail.Attachments.Add(data);
                    }
                }

                // add read receipt
                if (Properties.Settings.Default.ReadRcpt == true)
                {
                    mail.Headers.Add("Disposition-Notification-To", txtBoxEmailAddress.Text);
                }

                // set the content
                mail.Subject    = txtBoxSubject.Text;
                msgSubject      = txtBoxSubject.Text;
                mail.Body       = richTxtBody.Text;
                mail.IsBodyHtml = Properties.Settings.Default.BodyHtml;

                // add delivery notifications
                if (Properties.Settings.Default.DelNotifOnFailure == true)
                {
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                }

                if (Properties.Settings.Default.DelNotifOnSuccess == true)
                {
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                }

                // send by pickup folder?
                if (rdoSendByPickupFolder.Checked)
                {
                    if (chkBoxSpecificPickupFolder.Checked)
                    {
                        if (Directory.Exists(txtPickupFolder.Text))
                        {
                            smtp.DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                            smtp.PickupDirectoryLocation = txtPickupFolder.Text;
                        }
                        else
                        {
                            throw new DirectoryNotFoundException(@"The specified directory """ + txtPickupFolder.Text + @""" does not exist.");
                        }
                    }
                    else
                    {
                        smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                    }
                }

                // smtp client setup

                // this is for TLS enforcement -- is its true
                // STARTTLS will be utilized
                smtp.EnableSsl = chkEnableSSL.Checked;
                // we are avoiding to carry out default logon credentials to smtp session
                smtp.UseDefaultCredentials = false;

                smtp.Port = Int32.Parse(cmbPort.Text.Trim());
                smtp.Host = cmbServer.Text;

                smtp.Timeout = Properties.Settings.Default.SendSyncTimeout;

                // we are checking, if its office365.com or not because of specific settings on receive connectors
                // for on premise exchange servers can cause exception
                if (smtp.Host == "smtp.office365.com")
                {
                    string targetname = "SMTPSVC/" + smtp.Host;
                    smtp.TargetName = targetname;
                }
                else
                {
                    smtp.TargetName = null;
                }


                // check for credentials
                // moved credential a bit low in the code flow becuase of I've seen a credential removal somehow
                string sUser     = txtBoxEmailAddress.Text.Trim();
                string sPassword = mskPassword.Text.Trim();
                string sDomain   = txtBoxDomain.Text.Trim();

                if (sUser.Length != 0)
                {
                    if (sDomain.Length != 0)
                    {
                        smtp.Credentials = new NetworkCredential(sUser, sPassword, sDomain);
                    }
                    else
                    {
                        smtp.Credentials = new NetworkCredential(sUser, sPassword);
                    }
                }
                // send email
                smtp.Send(mail);
            }
            catch (SmtpException se)
            {
                txtBoxErrorLog.Clear();
                noErrFound = false;
                if (se.StatusCode == SmtpStatusCode.MailboxBusy || se.StatusCode == SmtpStatusCode.MailboxUnavailable)
                {
                    logger.Log("Delivery failed - retrying in 5 seconds.");
                    Thread.Sleep(5000);
                    smtp.Send(mail);
                }
                else
                {
                    logger.Log("Error: " + se.Message);
                    logger.Log("StackTrace: " + se.StackTrace);
                    logger.Log("Status Code: " + se.StatusCode);
                    logger.Log("Description:" + MessageUtilities.GetSmtpStatusCodeDescription(se.StatusCode.ToString()));
                    logger.Log("Inner Exception: " + se.InnerException);
                }
            }
            catch (InvalidOperationException ioe)
            {
                // invalid smtp address used
                txtBoxErrorLog.Clear();
                noErrFound = false;
                logger.Log("Error: " + ioe.Message);
                logger.Log("StackTrace: " + ioe.StackTrace);
                logger.Log("Inner Exception: " + ioe.InnerException);
            }
            catch (FormatException fe)
            {
                // invalid smtp address used
                txtBoxErrorLog.Clear();
                noErrFound = false;
                logger.Log("Error: " + fe.Message);
                logger.Log("StackTrace: " + fe.StackTrace);
                logger.Log("Inner Exception: " + fe.InnerException);
            }
            catch (Exception ex)
            {
                txtBoxErrorLog.Clear();
                noErrFound = false;
                logger.Log("Error: " + ex.Message);
                logger.Log("StackTrace: " + ex.StackTrace);
                logger.Log("Inner Exception: " + ex.InnerException);
            }
            finally
            {
                // log success
                if (formValidated == true && noErrFound == true)
                {
                    logger.Log("Message subject = " + msgSubject);
                    logger.Log("Message send = SUCCESS");
                }

                // cleanup resources
                mail.Dispose();
                mail = null;
                smtp.Dispose();
                smtp = null;

                // reset variables
                formValidated = false;
                noErrFound    = true;
                inlineAttachmentsTable.Clear();
                hdrName    = null;
                hdrValue   = null;
                msgSubject = null;
            }
        }