コード例 #1
0
ファイル: MailMergeMessage.cs プロジェクト: yogirajshakya/SMS
        /// <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;
        }
コード例 #2
0
 /// <summary>
 /// Sends a single mail merge message.
 /// </summary>
 /// <param name="mailMergeMessage">Message to send.</param>
 public void Send(MailMergeMessage mailMergeMessage)
 {
     lock (_locker)
     {
         Send(mailMergeMessage, false);
     }
 }
コード例 #3
0
 internal MailSenderBeforeSendEventArgs(Exception error, bool cancelled, MailMergeMessage mailMergeMessage,
                                        DateTime startTime)
 {
     Error            = error;
     Cancelled        = cancelled;
     MailMergeMessage = mailMergeMessage;
     StartTime        = startTime;
 }
コード例 #4
0
 internal MailSenderSendFailureEventArgs(Exception error, int failureCounter, int maxFailures, int retryDelayTime,
                                         MailMergeMessage mailMergeMessage)
 {
     Error            = error;
     FailureCounter   = failureCounter;
     MaxFailures      = maxFailures;
     RetryDelayTime   = retryDelayTime;
     MailMergeMessage = mailMergeMessage;
 }
コード例 #5
0
 /// <summary>
 /// Sends a single mail message asyncronously.
 /// </summary>
 /// <remarks>The method rises events before and after sending, as well as on send failure.</remarks>
 /// <param name="mailMergeMessage">Mail merge message.</param>
 public void SendAsync(MailMergeMessage mailMergeMessage)
 {
     _bgSender = new BackgroundWorker {
         WorkerSupportsCancellation = true
     };
     _bgSender.DoWork             += bgSender_DoSendSingle;
     _bgSender.RunWorkerCompleted += ((sender, e) => ((BackgroundWorker)sender).Dispose());
     _bgSender.RunWorkerAsync(mailMergeMessage);
 }
コード例 #6
0
 internal MailSenderMergeProgressEventArgs(DateTime startTime, int totalMsg, int sentMsg, int errorMsg,
                                           MailMergeMessage mailMergeMessage, bool completed)
 {
     StartTime        = startTime;
     TotalMsg         = totalMsg;
     SentMsg          = sentMsg;
     ErrorMsg         = errorMsg;
     MailMergeMessage = mailMergeMessage;
     Completed        = completed;
 }
コード例 #7
0
 /// <summary>
 /// Sends mail messages syncronously to all recipients supplied in the data source
 /// of the mail merge message.
 /// </summary>
 /// <param name="mailMergeMessage">Mail merge message.</param>
 public void SendAll(MailMergeMessage mailMergeMessage)
 {
     lock (_locker)
     {
         for (int i = 0; i < mailMergeMessage.DataItemCount; i++)
         {
             mailMergeMessage.CurrentDataPosition = i;
             Send(mailMergeMessage);
         }
     }
 }
コード例 #8
0
        /// <summary>
        /// Sends mail messages asyncronously to all recipients supplied in the data source
        /// of the mail merge message.
        /// </summary>
        /// <param name="mailMergeMessage">Mail merge message.</param>
        public void SendAllAsync(MailMergeMessage mailMergeMessage)
        {
            if (mailMergeMessage == null)
            {
                throw new NullReferenceException("MailMergeMessage must not be null.");
            }

            _bgSender = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            _bgSender.DoWork             += bgSender_DoSendMulti;
            _bgSender.RunWorkerCompleted += ((sender, e) => ((BackgroundWorker)sender).Dispose());
            _bgSender.RunWorkerAsync(mailMergeMessage);
        }
コード例 #9
0
ファイル: frmMain.cs プロジェクト: yogirajshakya/SMS
        private void Setup()
        {
            // read content
            string html = ReadHtmlText(_htmlFile);

            // insert your own e-mail address here!
            MailMergeAddress myMailAddress = new MailMergeAddress(MailAddressType.TestAddress,
                                    Helper.FromEmailAddress, Helper.FromEmailName, Encoding.Default);
            // create the mail message
            //_mmm = new MailMergeMessage("CRON Job Status Report for Domain '{DomainName:\"{0}{empty:[name not registered!]}\"}'", null, html);
            _mmm = new MailMergeMessage(_subject, _plainText, html, _fileAttachments);
            //_mmm.PlainText =_plainText;

            // adjust mail specific settings
            _mmm.CharacterEncoding = Encoding.GetEncoding("iso-8859-1");
            _mmm.CultureInfo = new System.Globalization.CultureInfo("en-US");
            _mmm.TextTransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
            _mmm.BinaryTransferEncoding = System.Net.Mime.TransferEncoding.Base64;

            // add recipients, from address and test address to use.
            // the address part of the test address will be used instead of the other addresses.
            _mmm.MailMergeAddresses.Add(new MailMergeAddress(MailAddressType.To, "<{Email}>", "{FirstName} {LastName}", Encoding.Default));
            _mmm.MailMergeAddresses.Add(new MailMergeAddress(MailAddressType.From, myMailAddress.Address, myMailAddress.DisplayName, Encoding.Default));
            _mmm.MailMergeAddresses.Add(myMailAddress);

            // base directory for html images
            _mmm.FileBaseDir = Helper.EmailHTMLFileImagesFolder; //GetMailDemoFilesDir();

            // setup the mail sender
            _mailSender = null;
            _mailSender = new MailMergeSender();

            SetupEventHandlers();

            //_mailSender.LocalHostName = "mail." + Environment.MachineName;
            _mailSender.MaxFailures = Helper.EmailMaxFailures;
            _mailSender.DelayBetweenMessages = Helper.EmailDelayBetweenMessages;

            _mailSender.MailOutputDirectory = _outputFolder;
            _mailSender.MessageOutput = Helper.EmailMessageOutput;  // change to MessageOutput.SmtpServer if you like, but be careful :)

            // smtp details - change to your demands
            _mailSender.SmtpHost = Helper.EmailSmtpHost;
            _mailSender.SmtpPort = Helper.EmailSmtpPort;
            _mailSender.SetSmtpAuthentification(Helper.EmailSmtpAuthentificationUserName, Helper.EmailSmtpAuthentificationPassword);
            _mailSender.LocalHostName = Helper.EmailLocalHostName;
        }
コード例 #10
0
 internal MailSenderMergeBeginEventArgs(DateTime startTime, MailMergeMessage mailMergeMessage)
 {
     StartTime        = startTime;
     MailMergeMessage = mailMergeMessage;
 }
コード例 #11
0
 /// <summary>
 /// Constructor.
 /// </summary>
 internal MailMergeAddressCollection(ref MailMergeMessage msg)
 {
     _mailMergeMessage = msg;
 }
コード例 #12
0
        /// <summary>
        /// This is the procedure taking care of sending the message.
        /// </summary>
        /// <param name="mailMergeMessage">Mail merge message to send.</param>
        /// <param name="isAsync">If true, no exceptions are thrown. If false, exceptions are thrown.</param>
        /// <exception>isAsync must be false for exceptions to be thrown.
        /// If the MailMergeMessage is the cause of the exception, MailMergeMessage.MailMergeMessageException is thrown.
        /// If the SMTP transaction is the cause, SmtpFailedRecipientsException, SmtpFailedRecipientException or SmtpException can be expected.
        /// </exception>
        private void Send(MailMergeMessage mailMergeMessage, bool isAsync)
        {
            PrepareSettings();
            DateTime    startTime     = DateTime.Now;
            Exception   sendException = null;
            MailMessage msg           = null;

            ReadySent = false;

            try
            {
                msg = mailMergeMessage.GetMailMessage();
            }
            catch (Exception ex)
            {
                sendException = ex;
                if (sendException.GetType() == typeof(MailMergeMessage.MailMergeMessageException))
                {
                    // get the message, although due to exceptions it will not be complete
                    msg = ((MailMergeMessage.MailMergeMessageException)sendException).MailMessage;
                }
            }

            // the client can rely on the sequence of events: OnBeforeSend, OnSendFailure (if any), OnAfterSend
            if (OnBeforeSend != null)
            {
                OnBeforeSend(_smtp, new MailSenderBeforeSendEventArgs(sendException, _sendCancel, mailMergeMessage, startTime));
            }

            // if there was an exception in building the message and sender is running asnc,
            // only trigger events and return
            if (sendException != null)
            {
                if (OnSendFailure != null)
                {
                    OnSendFailure(_smtp, new MailSenderSendFailureEventArgs(sendException, 1, 1, 0, mailMergeMessage));
                }
                if (OnAfterSend != null)
                {
                    OnAfterSend(_smtp,
                                new MailSenderAfterSendEventArgs(sendException, _sendCancel, mailMergeMessage, startTime, DateTime.Now));
                }
                ReadySent = true;

                if (!isAsync)
                {
                    throw sendException;
                }

                return;
            }

            int failureCounter = 0;

            do
            {
                try
                {
                    sendException = null;
                    if (MessageOutput != MessageOutput.None)
                    {
                        _smtp.Send(msg);

                        foreach (Attachment att in msg.Attachments)                         // 2010-09-08, thanks to floritheripper
                        {
                            att.Dispose();
                        }

                        // Fix by Abdelkrim 2009-02-04: when _smtp.Send throws less than _maxFailures exceptions,
                        // and succeeds after an exception, we MUST break the while loop here (else: infinite)
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (ex.GetType() == typeof(SmtpFailedRecipientsException) || ex.GetType() == typeof(SmtpFailedRecipientException) ||
                        ex.GetType() == typeof(SmtpException))
                    {
                        failureCounter++;
                        sendException = ex;
                        if (OnSendFailure != null)
                        {
                            OnSendFailure(_smtp,
                                          new MailSenderSendFailureEventArgs(sendException, failureCounter, _maxFailures, _retryDelayTime,
                                                                             mailMergeMessage));
                        }
                        Thread.Sleep(_retryDelayTime);
                    }
                    else
                    {
                        failureCounter = _maxFailures;
                        sendException  = ex;
                        if (OnSendFailure != null)
                        {
                            OnSendFailure(_smtp, new MailSenderSendFailureEventArgs(sendException, 1, 1, 0, mailMergeMessage));
                        }
                    }
                }
            } while (failureCounter < _maxFailures && failureCounter > 0);

            if (OnAfterSend != null)
            {
                OnAfterSend(_smtp,
                            new MailSenderAfterSendEventArgs(sendException, _sendCancel, mailMergeMessage, startTime, DateTime.Now));
            }

            ReadySent = true;

            if (sendException != null && !isAsync)
            {
                throw sendException;
            }
        }
コード例 #13
0
 public void SendAsync(MailMergeMessage mailMergeMessage, DataTable mailDataTable)
 {
     mailMergeMessage.DataSource = mailDataTable;
     SendAllAsync(mailMergeMessage);
 }