Пример #1
0
 public EmailMessageTask(SmtpSettings smtpSettings)
 {
     User = smtpSettings.User;
     Password = smtpSettings.Password;
     Server = smtpSettings.Server;
     Port = smtpSettings.Port;
     RequiresAuthentication = smtpSettings.RequiresAuthentication;
     UseSsl = smtpSettings.UseSsl;
     PreferredEncoding = smtpSettings.PreferredEncoding;
 }
Пример #2
0
        private void RunTask()
        {
            if (IsValid())
            {
                try
                {
                    SmtpSettings smtpSettings = new SmtpSettings();
                    smtpSettings.Password = password;
                    smtpSettings.Port = port;
                    smtpSettings.PreferredEncoding = preferredEncoding;
                    smtpSettings.RequiresAuthentication = requiresAuthentication;
                    smtpSettings.UseSsl = useSsl;
                    smtpSettings.User = user;
                    smtpSettings.Server = server;

                    string messageBody;
                    if (useHtml)
                    {
                        messageBody = htmlBody;
                    }
                    else
                    {
                        messageBody = textBody;
                    }

                    Email.Send(
                        smtpSettings,
                        emailFrom,
                        emailFromAlias,
                        emailReplyTo,
                        emailTo,
                        emailCc,
                        emailBcc,
                        subject,
                        messageBody,
                        useHtml,
                        emailPriority);
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }

            ReportStatus();
        }
Пример #3
0
        private void SendLetter(
            SmtpSettings smtpSettings,
            LetterInfo letterInfo, 
            Letter letter, 
            LetterSubscriber subscriber)
        {
            // TODO: use multi part email with both html and plain text body
            // instead of this either or approach

            bool testMode = false;

            if (
                (ConfigurationManager.AppSettings["NewsletterTestMode"] != null)
                && (ConfigurationManager.AppSettings["NewsletterTestMode"] == "true")
                )
            {
                testMode = true;
            }

            LetterSendLog mailLog = new LetterSendLog();
            mailLog.EmailAddress = subscriber.EmailAddress;
            mailLog.LetterGuid = letter.LetterGuid;
            mailLog.UserGuid = subscriber.UserGuid;

            if (testMode)
            {
                Thread.Sleep(3000); // sleep 3 seconds per message to simulate
            }
            else
            {
                try
                {
                    if (subscriber.UseHtml)
                    {
                        Email.SendEmail(
                            smtpSettings,
                            letterInfo.FromAddress,
                            subscriber.EmailAddress,
                            string.Empty,
                            string.Empty,
                            letter.Subject,
                            ReplaceHtmlTokens(letter.HtmlBody, subscriber),
                            subscriber.UseHtml,
                            "Normal");
                    }
                    else
                    {
                        Email.SendEmail(
                            smtpSettings,
                            letterInfo.FromAddress,
                            subscriber.EmailAddress,
                            string.Empty,
                            string.Empty,
                            letter.Subject,
                            ReplaceTextTokens(letter.TextBody, subscriber),
                            subscriber.UseHtml,
                            "Normal");

                    }
                }
                catch (Exception ex)
                {
                    // TODO: catch more specific exception(s) figure out what ones can be thrown here
                    mailLog.ErrorOccurred = true;
                    mailLog.ErrorMessage = ex.ToString();
                    log.Error(ex);

                }
            }

            mailLog.Save();
        }
Пример #4
0
        private void RunTask()
        {
            Letter letter = new Letter(this.letterGuid);
            if (letter.LetterGuid == Guid.Empty) return;
            if (letter.SendCompleteUtc > DateTime.MinValue) return;
            if (letter.SendClickedUtc == DateTime.MinValue) return;

            LetterInfo letterInfo = new LetterInfo(letter.LetterInfoGuid);

            // TODO: this could be a very large recordset if the kist is very large
            // might be better to get a page at a time instead of all at once.

            List<LetterSubscriber> subscribers
                = LetterSubscriber.GetSubscribersNotSentYet(
                letter.LetterGuid,
                letter.LetterInfoGuid);

            nextStatusUpdateTime = DateTime.UtcNow.AddSeconds(updateFrequency);
            totalSubscribersToSend = subscribers.Count;

            if ((totalSubscribersToSend > 0) && (letter.SendStartedUtc == DateTime.MinValue))
            {
                letter.TrackSendStarted();
            }

            SmtpSettings smtpSettings = new SmtpSettings();
            smtpSettings.Password = password;
            smtpSettings.Port = port;
            smtpSettings.PreferredEncoding = preferredEncoding;
            smtpSettings.RequiresAuthentication = requiresAuthentication;
            smtpSettings.UseSsl = useSsl;
            smtpSettings.User = user;
            smtpSettings.Server = server;

            foreach (LetterSubscriber subscriber in subscribers)
            {
                SendLetter(smtpSettings, letterInfo, letter, subscriber);
                subscribersSentSoFar += 1;

                if (DateTime.UtcNow > nextStatusUpdateTime)
                    ReportStatus();

            }

            ReportStatus();
        }
Пример #5
0
        public static bool Send(SmtpSettings smtpSettings, MailMessage message, out string result)
        {
            if (message.To.ToString() == "*****@*****.**")
            {
                //demo site
                result = "can't use [email protected] email address";
                return(false);
            }

            string globalBcc = GetGlobalBccAddress();

            if (globalBcc.Length > 0)
            {
                MailAddress bcc = new MailAddress(globalBcc);
                message.Bcc.Add(bcc);
            }

            int        timeoutMilliseconds = ConfigHelper.GetIntProperty("SMTPTimeoutInMilliseconds", 15000);
            SmtpClient smtpClient          = new SmtpClient(smtpSettings.Server, smtpSettings.Port);

            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.EnableSsl      = smtpSettings.UseSsl;
            smtpClient.Timeout        = timeoutMilliseconds;

            if (smtpSettings.RequiresAuthentication)
            {
                NetworkCredential smtpCredential
                    = new NetworkCredential(
                          smtpSettings.User,
                          smtpSettings.Password);

                CredentialCache myCache = new CredentialCache();
                myCache.Add(smtpSettings.Server, smtpSettings.Port, "LOGIN", smtpCredential);

                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials           = myCache;
            }
            else
            {
                //aded 2010-01-22 JA
                smtpClient.UseDefaultCredentials = true;
            }


            try
            {
                smtpClient.Send(message);
                //log.Debug("Sent Message: " + subject);
                //log.Info("Sent Message: " + subject);

                bool logEmail = ConfigHelper.GetBoolProperty("LogAllEmailsWithSubject", false);

                if (logEmail)
                {
                    log.Info("Sent message " + message.Subject + " to " + message.To[0].Address);
                }
                result = "sent";
                return(true);
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                //log.Error("error sending email to " + to + " from " + from, ex);
                result = $"error: {ex}";
                log.Error("error sending email to " + message.To.ToString() + " from " + message.From.ToString() + ", will retry", ex);
                return(RetrySend(message, smtpClient, ex));
            }
            catch (WebException ex)
            {
                result = $"error: {ex}";
                log.Error("error sending email to " + message.To.ToString() + " from " + message.From.ToString() + ", message was: " + message.Body, ex);
                return(false);
            }
            catch (SocketException ex)
            {
                result = $"error: {ex}";
                log.Error("error sending email to " + message.To.ToString() + " from " + message.From.ToString() + ", message was: " + message.Body, ex);
                return(false);
            }
            catch (InvalidOperationException ex)
            {
                result = $"error: {ex}";
                log.Error("error sending email to " + message.To.ToString() + " from " + message.From.ToString() + ", message was: " + message.Body, ex);
                return(false);
            }
            catch (FormatException ex)
            {
                result = $"error: {ex}";
                log.Error("error sending email to " + message.To.ToString() + " from " + message.From.ToString() + ", message was: " + message.Body, ex);
                return(false);
            }
        }
Пример #6
0
 public static bool Send(SmtpSettings smtpSettings, MailMessage message)
 {
     return(Send(smtpSettings, message, out _));
 }
Пример #7
0
        public static bool Send(
            SmtpSettings smtpSettings,
            string from,
            string fromAlias,
            string replyTo,
            string to,
            string cc,
            string bcc,
            string subject,
            string messageBody,
            bool html,
            string priority,
            List <Attachment> attachments,
            out string result)
        {
            if (to == "*****@*****.**")
            {
                //demo site
                result = "can't use [email protected] email address";
                return(false);
            }

            if ((ConfigurationManager.AppSettings["DisableSmtp"] != null) && (ConfigurationManager.AppSettings["DisableSmtp"] == "true"))
            {
                result = "Not Sending email because DisableSmtp is true in config.";
                log.Info(result);
                return(false);
            }

            if ((smtpSettings == null) || (!smtpSettings.IsValid))
            {
                result = "Invalid smtp settings detected in Email.Send ";
                log.Error(result);
                return(false);
            }

            if (debugLog)
            {
                log.Debug($"In Email.Send({from}, {to}, {cc}, {bcc}, {subject}, {messageBody}, {html}, {priority})");
            }

            using (MailMessage mail = new MailMessage())
            {
                SetMessageEncoding(smtpSettings, mail);


                MailAddress fromAddress;
                try
                {
                    if (fromAlias.Length > 0)
                    {
                        fromAddress = new MailAddress(from, fromAlias);
                    }
                    else
                    {
                        fromAddress = new MailAddress(from);
                    }
                }
                catch (ArgumentException)
                {
                    result = $"invalid from address {from}";
                    log.Error(result);
                    log.Info("no valid from address was provided so not sending message " + messageBody);
                    return(false);
                }
                catch (FormatException)
                {
                    result = $"invalid from address {from}";
                    log.Error(result);
                    log.Info("no valid from address was provided so not sending message " + messageBody);
                    return(false);
                }

                mail.From = fromAddress;

                List <string> toAddresses = to.Replace(";", ",").SplitOnChar(',');
                foreach (string toAddress in toAddresses)
                {
                    try
                    {
                        MailAddress a = new MailAddress(toAddress);
                        mail.To.Add(a);
                    }
                    catch (ArgumentException)
                    {
                        log.Error("ignoring invalid to address " + toAddress);
                    }
                    catch (FormatException)
                    {
                        log.Error("ignoring invalid to address " + toAddress);
                    }
                }

                if (mail.To.Count == 0)
                {
                    result = $"no valid to address was provided so not sending message {messageBody}";
                    log.Error(result);
                    return(false);
                }

                if (replyTo.Length > 0)
                {
                    try
                    {
                        MailAddress replyAddress = new MailAddress(replyTo);
                        mail.ReplyTo = replyAddress;
                    }
                    catch (ArgumentException)
                    {
                        log.Error("ignoring invalid replyto address " + replyTo);
                    }
                    catch (FormatException)
                    {
                        log.Error("ignoring invalid replyto address " + replyTo);
                    }
                }

                if (cc.Length > 0)
                {
                    List <string> ccAddresses = cc.Replace(";", ",").SplitOnChar(',');

                    foreach (string ccAddress in ccAddresses)
                    {
                        try
                        {
                            MailAddress a = new MailAddress(ccAddress);
                            mail.CC.Add(a);
                        }
                        catch (ArgumentException)
                        {
                            log.Error("ignoring invalid cc address " + ccAddress);
                        }
                        catch (FormatException)
                        {
                            log.Error("ignoring invalid cc address " + ccAddress);
                        }
                    }
                }

                if (bcc.Length > 0)
                {
                    List <string> bccAddresses = bcc.Replace(";", ",").SplitOnChar(',');

                    foreach (string bccAddress in bccAddresses)
                    {
                        try
                        {
                            MailAddress a = new MailAddress(bccAddress);
                            mail.Bcc.Add(a);
                        }
                        catch (ArgumentException)
                        {
                            log.Error("invalid bcc address " + bccAddress);
                        }
                        catch (FormatException)
                        {
                            log.Error("invalid bcc address " + bccAddress);
                        }
                    }
                }

                mail.Subject = subject.RemoveLineBreaks();

                switch (priority)
                {
                case PriorityHigh:
                    mail.Priority = MailPriority.High;
                    break;

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

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



                if (html)
                {
                    mail.IsBodyHtml = true;
                    // this char can reportedly cause problems in some email clients so replace it if it exists
                    mail.Body = messageBody.Replace("\xA0", "&nbsp;");
                }
                else
                {
                    mail.Body = messageBody;
                }

                // add attachments if there are any
                if (attachments != null)
                {
                    foreach (Attachment a in attachments)
                    {
                        mail.Attachments.Add(a);
                    }
                }

                if (smtpSettings.AddBulkMailHeader)
                {
                    mail.Headers.Add("Precedence", "bulk");
                }


                return(Send(smtpSettings, mail, out result));
            }// end using MailMessage
        }