/// <summary>
        /// Creates an empty mail merge message.
        /// </summary>
        public MailMergeMessage()
        {
            IgnoreEmptyRecipientAddr    = true;
            DeliveryNotificationOptions = DeliveryNotificationOptions.None;
            Priority               = MailPriority.Normal;
            Xmailer                = null;
            Headers                = new NameValueCollection();
            StringAttachments      = new List <StringAttachment>();
            FileAttachments        = new List <FileAttachment>();
            StreamAttachments      = new List <StreamAttachment>();
            BinaryTransferEncoding = TransferEncoding.Base64;
            TextTransferEncoding   = TransferEncoding.SevenBit;
            CharacterEncoding      = Encoding.Default;

            _textVariableManager = new TextVariableManager
            {
                CultureInfo = CultureInfo,
                ShowNullAs  = string.Empty,
                ShowEmptyAs = string.Empty
            };

            _textVariableManager.GetBindingSource().CurrentChanged     += RaiseDataChangedEvent;
            _textVariableManager.GetBindingSource().CurrentItemChanged += RaiseDataChangedEvent;
            _textVariableManager.GetBindingSource().PositionChanged    += RaiseDataChangedEvent;
            _textVariableManager.GetBindingSource().ListChanged        += RaiseDataChangedEvent;

            MailMergeMessage msg = this;

            MailMergeAddresses = new MailMergeAddressCollection(ref msg);

            FileBaseDir = Environment.CurrentDirectory;
        }
Exemple #2
0
        public string ToString(MailAddressType addrType)
        {
            TextVariableManager txtMgr = _mailMergeMessage.GetTextVariableManager().Clone();

            txtMgr.ShowEmptyAs = txtMgr.ShowNullAs = string.Empty;
            var addr = new StringBuilder();

            foreach (MailMergeAddress mmAddr in Get(addrType))
            {
                // copy all bad file names and bad variable names from "main" TextVariableManager
                txtMgr.BadFiles.AddRange(_mailMergeMessage.GetTextVariableManager().BadFiles);
                txtMgr.BadVariables.AddRange(_mailMergeMessage.GetTextVariableManager().BadVariables);

                mmAddr.TextVariableManager = txtMgr;
                addr.Append(mmAddr.ToString());

                // fill the "main" TextVariableManager with bad file/variable names
                _mailMergeMessage.GetTextVariableManager().BadFiles.Clear();
                _mailMergeMessage.GetTextVariableManager().BadFiles.AddRange(txtMgr.BadFiles);

                _mailMergeMessage.GetTextVariableManager().BadVariables.Clear();
                _mailMergeMessage.GetTextVariableManager().BadVariables.AddRange(txtMgr.BadVariables);

                addr.Append(", ");
            }

            if (addr.Length >= 2)
            {
                addr.Remove(addr.Length - 2, 2);
            }

            return(addr.ToString());
        }
        /// <summary>
        /// Replaces the text variables by their formatted values.
        /// The original text in the argument remains unchanged.
        /// </summary>
        private StringBuilder ReplaceTextVariablesWithValues(StringBuilder text, List <Variable> textVariables)
        {
            // work on a copy of the orginal text
            var textResult = new StringBuilder(text.ToString());

            if (textResult.Length == 0)
            {
                return(textResult);
            }

            // first read in all external files - this is done only once - no recursion.
            bool textFileWasIncluded = false;

            foreach (Variable variable in textVariables.Where(variable => !string.IsNullOrEmpty(variable.Format) && _formatAsFilename == variable.Format.ToLower()))
            {
                // If a format name called "file" is found, the variable's value is interpreted as a file name
                // The file name may contain variables as well.
                using (TextVariableManager tvm = Clone())
                {
                    string filename = tvm.Process(variable.Value as string ?? string.Empty);
                    // add all new bad variable names to the list
                    foreach (string badVar in tvm.BadVariables.Where(badVar => !BadVariables.Contains(badVar)))
                    {
                        BadVariables.Add(badVar);
                    }
                    filename = MakeFullPath(filename);
                    string content = ReadFile(filename);

                    if (content == null)
                    {
                        if (FileVariableErrors == VariableError.ReplaceWithEmptyString)
                        {
                            textResult = textResult.Replace(variable.MatchingString, string.Empty);
                        }
                    }
                    else
                    {
                        textResult = textResult.Replace(variable.MatchingString, content);
                    }

                    textFileWasIncluded = true;
                }
            }

            // if a text file was included, re-search and replace the text for variables
            if (textFileWasIncluded)
            {
                foreach (Variable variable in SearchTextVariables(textResult).Where(variable => variable.Format != _formatAsFilename || FileVariableErrors != VariableError.ShowTextVariable))
                {
                    textResult = textResult.Replace(variable.MatchingString, variable.ToString());
                }
            }

            // Next replace variables for the whole text (including any text files read before).
            // If a text file was included, it could again contain variables - but do NOT process
            // external text files recursively.

            return(textVariables.Aggregate(textResult, (current, variable) => current.Replace(variable.MatchingString, variable.ToString())));
        }
        /// <summary>
        /// Prepares all recipient address and the corresponding header fields of a mail message.
        /// </summary>
        private void AddAddressesToMailMessage()
        {
            #region *** Clear MailMessage headers ***

            /*
             * Not really necessary because we always work on a NEW instance of a MailMessage
             */

            //cc, _bcc, _sender, _from, _replyto;
            _mailMessage.To.Clear();
            _mailMessage.CC.Clear();
            _mailMessage.Bcc.Clear();
            _mailMessage.ReplyToList.Clear();
            _mailMessage.Sender = null;

            #endregion

            _badMailAddr.Clear();

            MailMergeAddress testAddress = null;
            foreach (MailMergeAddress mmAddr in MailMergeAddresses.Where(mmAddr => mmAddr.AddrType == MailAddressType.TestAddress))
            {
                testAddress = new MailMergeAddress(MailAddressType.TestAddress, mmAddr.Address, mmAddr.DisplayName,
                                                   mmAddr.DisplayNameCharacterEncoding);
            }

            // ShowNullsAs MUST be string.empty with email addresses!
            TextVariableManager txtMgr = _textVariableManager.Clone();
            txtMgr.ShowNullAs = txtMgr.ShowEmptyAs = string.Empty;

            foreach (MailMergeAddress mmAddr in MailMergeAddresses)
            {
                try
                {
                    MailAddress mailAddr;
                    // use the address part the test mail address (if set) but use the original display name
                    if (testAddress != null)
                    {
                        testAddress.DisplayName         = mmAddr.DisplayName;
                        testAddress.TextVariableManager = txtMgr;
                        mailAddr = testAddress.GetMailAddress();
                    }
                    else
                    {
                        mmAddr.TextVariableManager = txtMgr;
                        mailAddr = mmAddr.GetMailAddress();
                    }

                    _badVariableNames.AddRange(txtMgr.BadVariables);
                    _badInlineFiles.AddRange(txtMgr.BadFiles);

                    if (IgnoreEmptyRecipientAddr && mailAddr == null)
                    {
                        continue;
                    }

                    switch (mmAddr.AddrType)
                    {
                    case MailAddressType.To:
                        _mailMessage.To.Add(mailAddr);
                        break;

                    case MailAddressType.CC:
                        _mailMessage.CC.Add(mailAddr);
                        break;

                    case MailAddressType.Bcc:
                        _mailMessage.Bcc.Add(mailAddr);
                        break;

                    case MailAddressType.ReplyTo:
                        _mailMessage.ReplyToList.Add(mailAddr);
                        break;

                    case MailAddressType.ConfirmReadingTo:
                        _mailMessage.Headers.Remove(CConfirmReading);
                        _mailMessage.Headers.Remove(CDispositionNotification);
                        _mailMessage.Headers.Add(CConfirmReading, mailAddr.Address);
                        _mailMessage.Headers.Add(CDispositionNotification, mailAddr.Address);
                        break;

                    case MailAddressType.ReturnReceiptTo:
                        _mailMessage.Headers.Remove(CReturnReceipt);
                        _mailMessage.Headers.Add(CReturnReceipt, mailAddr.Address);
                        break;

                    case MailAddressType.Sender:
                        _mailMessage.Sender = mailAddr;
                        break;

                    case MailAddressType.From:
                        _mailMessage.From = mailAddr;
                        break;
                    }
                }
                catch (FormatException)
                {
                    _badMailAddr.Add(mmAddr.ToString());
                }
            }
        }