/// <summary>
        /// Updates an email account
        /// </summary>
        /// <param name="emailAccount">Email account</param>
        public virtual void UpdateEmailAccount(EmailAccount emailAccount)
        {
            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

			emailAccount.Email = emailAccount.Email.EmptyNull();
			emailAccount.DisplayName = emailAccount.DisplayName.EmptyNull();
			emailAccount.Host = emailAccount.Host.EmptyNull();
			emailAccount.Username = emailAccount.Username.EmptyNull();
			emailAccount.Password = emailAccount.Password.EmptyNull();

            emailAccount.Email = emailAccount.Email.Trim();
            emailAccount.DisplayName = emailAccount.DisplayName.Trim();
            emailAccount.Host = emailAccount.Host.Trim();
            emailAccount.Username = emailAccount.Username.Trim();
            emailAccount.Password = emailAccount.Password.Trim();

			emailAccount.Email = emailAccount.Email.Truncate(255);
			emailAccount.DisplayName = emailAccount.DisplayName.Truncate(255);
			emailAccount.Host = emailAccount.Host.Truncate(255);
			emailAccount.Username = emailAccount.Username.Truncate(255);
			emailAccount.Password = emailAccount.Password.Truncate(255);

            _emailAccountRepository.Update(emailAccount);

            //event notification
            _eventPublisher.EntityUpdated(emailAccount);
        }
Exemple #2
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main(string[] args)
        {

            HostFactory.Run(x =>
            {
                x.UseNLog();
                x.AddCommandLineDefinition("nd", u => { RunDownloader = false; });
                x.AddCommandLineDefinition("u", u => { TestAccount = new EmailAccount() { Username = u }; });
                x.AddCommandLineDefinition("pw", p => { TestAccount.Password = p; });
                x.AddCommandLineDefinition("t", t => { TestAccount.Type = t; });
                x.AddCommandLineDefinition("s", s => { TestAccount.Server = s; });
                x.AddCommandLineDefinition("pt", p => { TestAccount.Port = int.Parse(p); });
                x.ApplyCommandLine();
                x.Service<ServiceRunner>(s =>
                {
                    s.ConstructUsing(name => new ServiceRunner());
                    s.WhenStarted(ds => ds.Start());
                    s.WhenStopped(ds => ds.Stop());
                });

            });

            Console.Read();

        }
        /// <summary>
        /// Inserts an email account
        /// </summary>
        /// <param name="emailAccount">Email account</param>
        public virtual void InsertEmailAccount(EmailAccount emailAccount)
        {
            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            emailAccount.Email = CommonHelper.EnsureNotNull(emailAccount.Email);
            emailAccount.DisplayName = CommonHelper.EnsureNotNull(emailAccount.DisplayName);
            emailAccount.Host = CommonHelper.EnsureNotNull(emailAccount.Host);
            emailAccount.Username = CommonHelper.EnsureNotNull(emailAccount.Username);
            emailAccount.Password = CommonHelper.EnsureNotNull(emailAccount.Password);

            emailAccount.Email = emailAccount.Email.Trim();
            emailAccount.DisplayName = emailAccount.DisplayName.Trim();
            emailAccount.Host = emailAccount.Host.Trim();
            emailAccount.Username = emailAccount.Username.Trim();
            emailAccount.Password = emailAccount.Password.Trim();

            emailAccount.Email = CommonHelper.EnsureMaximumLength(emailAccount.Email, 255);
            emailAccount.DisplayName = CommonHelper.EnsureMaximumLength(emailAccount.DisplayName, 255);
            emailAccount.Host = CommonHelper.EnsureMaximumLength(emailAccount.Host, 255);
            emailAccount.Username = CommonHelper.EnsureMaximumLength(emailAccount.Username, 255);
            emailAccount.Password = CommonHelper.EnsureMaximumLength(emailAccount.Password, 255);

            emailAccount.CreationDate = DateTime.Now;
            emailAccount.ModifiedDate = DateTime.Now;

            _emailAccountRepository.Insert(emailAccount);
        }
        public void Can_save_and_load_emailAccount()
        {
            var emailAccount = new EmailAccount
            {
                Email = "*****@*****.**",
                DisplayName = "Administrator",
                Host = "127.0.0.1",
                Port = 125,
                Username = "******",
                Password = "******",
                EnableSsl = true,
                UseDefaultCredentials = true
            };

            var fromDb = SaveAndLoadEntity(emailAccount);
            fromDb.ShouldNotBeNull();
            fromDb.Email.ShouldEqual("*****@*****.**");
            fromDb.DisplayName.ShouldEqual("Administrator");
            fromDb.Host.ShouldEqual("127.0.0.1");
            fromDb.Port.ShouldEqual(125);
            fromDb.Username.ShouldEqual("John");
            fromDb.Password.ShouldEqual("111");
            fromDb.EnableSsl.ShouldBeTrue();
            fromDb.UseDefaultCredentials.ShouldBeTrue();
        }
        /// <summary>
        /// Deletes an email account
        /// </summary>
        /// <param name="emailAccount">Email account</param>
        public virtual void DeleteEmailAccount(EmailAccount emailAccount)
        {
            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            if (GetAllEmailAccounts().Count == 1)
                throw new AaronException("You cannot delete this email account. At least one account is required.");

            _emailAccountRepository.Delete(emailAccount);
        }
        public SmtpContext(EmailAccount account)
        {
            Guard.ArgumentNotNull(() => account);

            this.Host = account.Host;
            this.Port = account.Port;
            this.EnableSsl = account.EnableSsl;
            this.Password = account.Password;
            this.UseDefaultCredentials = account.UseDefaultCredentials;
            this.Username = account.Username;
        }
        public virtual EmailAccount GetDefaultEmailAccount()
        {
            if (_defaultEmailAccount == null)
            {
                _defaultEmailAccount = GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
                if (_defaultEmailAccount == null)
                {
                    _defaultEmailAccount = GetAllEmailAccounts().FirstOrDefault();
                }
            }

            return _defaultEmailAccount;
        }
 /// <summary>
 /// Konstruktor
 /// </summary>
 public EMailHelper()
 {
     DefaultAccount = new EmailAccount
     {
         DisplayName = "Instant Delivery",
         Email = ConfigurationManager.AppSettings["NotificationEmailUsername"],
         EnableSsl = true,
         UseDefaultCredentials = false,
         Password = ConfigurationManager.AppSettings["NotificationEmailPassword"],
         Username = ConfigurationManager.AppSettings["NotificationEmailUsername"],
         Host = "smtp.gmail.com",
         Port = 587
     };
 }
 static EMailHelper()
 {
     DefaultAccount = new EmailAccount
     {
         DisplayName = "Instep Technologies",
         Email = "*****@*****.**",
         EnableSsl = true,
         UseDefaultCredentials = false,
         Password = "******",
         Username = "******",
         Host = "smtp.gmail.com",
         Port = 587
     };
 }
        public virtual void DeleteEmailAccount(EmailAccount emailAccount)
        {
            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            if (GetAllEmailAccounts().Count == 1)
                throw new SmartException("You cannot delete this email account. At least one account is required.");

            _emailAccountRepository.Delete(emailAccount);

            _cacheManager.RemoveByPattern(EMAILACCOUNT_PATTERN_KEY);
            _defaultEmailAccount = null;

            _eventPublisher.EntityDeleted(emailAccount);
        }
Exemple #11
0
        public MailSettings(ref string sAccount)
        {
            InitializeComponent();

            _settings = new eMDIeMailSettings();
            _sRecipient = _settings.Recipient;

            _session = new OutlookSession();
            _account = _session.EmailAccounts[_settings.MailAccount];

            if (_settings.syncInBackground)
                chkSendRcvInBackground.Checked = true;
            else
                chkSendRcvInBackground.Checked = false;

            fillAccountList();
        }
Exemple #12
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="from">From address</param>
        /// <param name="to">To address</param>
        /// <param name="replyTo"></param>
        /// <param name="bcc">BCC addresses list</param>
        /// <param name="cc">CC addresses ist</param>
        private static void SendEmail(EmailAccount emailAccount, string subject, string body,
                                       MailAddress from, MailAddress to, string replyTo,
                                      IEnumerable<string> bcc = null, IEnumerable<string> cc = null)
        {
            var message = new MailMessage { From = @from };
            message.To.Add(to);
            if (!string.IsNullOrEmpty(replyTo))
                message.ReplyToList.Add(new MailAddress(replyTo));

            if (null != bcc)
            {
                foreach (var address in bcc.Where(bccValue => !string.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(address.Trim());
                }
            }
            if (null != cc)
            {
                foreach (var address in cc.Where(ccValue => !string.IsNullOrWhiteSpace(ccValue)))
                {
                    message.CC.Add(address.Trim());
                }
            }
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = true;

            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host = emailAccount.Host;
                smtpClient.Port = emailAccount.Port;
                smtpClient.EnableSsl = emailAccount.EnableSsl;
                smtpClient.Credentials = emailAccount.UseDefaultCredentials ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(emailAccount.Username, emailAccount.Password);

                try
                {
                    smtpClient.Send(message);
                }
                catch (Exception)
                {
                    throw new Exception("Sending an email failed.");
                }
            }
        }
        protected int SendNotification(
			MessageTemplate messageTemplate,
            EmailAccount emailAccount, 
			int languageId, 
			IEnumerable<Token> tokens,
            string toEmailAddress, 
			string toName,
			string replyTo = null,
			string replyToName = null)
        {
            // retrieve localized message template data
            var bcc = messageTemplate.GetLocalized((mt) => mt.BccEmailAddresses, languageId);
            var subject = messageTemplate.GetLocalized((mt) => mt.Subject, languageId);
            var body = messageTemplate.GetLocalized((mt) => mt.Body, languageId);
			
            // Replace subject and body tokens 
            var subjectReplaced = _tokenizer.Replace(subject, tokens, false);
            var bodyReplaced = _tokenizer.Replace(body, tokens, true);
			
            bodyReplaced = WebHelper.MakeAllUrlsAbsolute(bodyReplaced, _httpRequest);

            var email = new QueuedEmail
            {
                Priority = 5,
                From = emailAccount.Email,
                FromName = emailAccount.DisplayName,
                To = toEmailAddress,
                ToName = toName,
                CC = string.Empty,
                Bcc = bcc,
				ReplyTo = replyTo,
				ReplyToName = replyToName,
                Subject = subjectReplaced,
                Body = bodyReplaced,
                CreatedOnUtc = DateTime.UtcNow,
                EmailAccountId = emailAccount.Id,
				SendManually = messageTemplate.SendManually
            };

            _queuedEmailService.InsertQueuedEmail(email);
            return email.Id;
        }
Exemple #14
0
 public sendMail()
 {
     session = new OutlookSession();
     //eMail = new EmailMessage();
     bool bFound = false;
     foreach (Account acc in session.EmailAccounts)
     {
         System.Diagnostics.Debug.WriteLine(acc.Name);
         if (acc.Name == "Google Mail")
             bFound = true;
     }
     if (bFound)
         account = session.EmailAccounts["Google Mail"];
     else
     {
         if(this.createAccountGoogle())
             account = session.EmailAccounts["Google Mail"];
     }
     if (account != null)
         _bIsValidAccount = true;
 }
Exemple #15
0
        public void SendEmail(EmailAccount emailAccount, string subject, string body, System.Net.Mail.MailAddress from, System.Net.Mail.MailAddress to, IEnumerable<string> bcc = null, IEnumerable<string> cc = null)
        {
            var message = new MailMessage();
            message.From = from;
            message.To.Add(to);
            if (null != bcc)
            {
                foreach (var address in bcc.Where(bccValue => !String.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(address.Trim());
                }
            }
            if (null != cc)
            {
                foreach (var address in cc.Where(ccValue => !String.IsNullOrWhiteSpace(ccValue)))
                {
                    message.CC.Add(address.Trim());
                }
            }
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = true;

            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host = emailAccount.Host;
                smtpClient.Port = emailAccount.Port;
                smtpClient.EnableSsl = emailAccount.EnableSsl;
                if (emailAccount.UseDefaultCredentials)
                    smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                else
                    smtpClient.Credentials = new NetworkCredential(emailAccount.Username, emailAccount.Password);
                smtpClient.Send(message);
            }
        }
        public virtual void InsertEmailAccount(EmailAccount emailAccount)
        {
            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            emailAccount.Email = emailAccount.Email.EmptyNull();
            emailAccount.DisplayName = emailAccount.DisplayName.EmptyNull();
            emailAccount.Host = emailAccount.Host.EmptyNull();
            emailAccount.Username = emailAccount.Username.EmptyNull();
            emailAccount.Password = emailAccount.Password.EmptyNull();

            emailAccount.Email = emailAccount.Email.Trim();
            emailAccount.DisplayName = emailAccount.DisplayName.Trim();
            emailAccount.Host = emailAccount.Host.Trim();
            emailAccount.Username = emailAccount.Username.Trim();
            emailAccount.Password = emailAccount.Password.Trim();

            emailAccount.Email = emailAccount.Email.Truncate(255);
            emailAccount.DisplayName = emailAccount.DisplayName.Truncate(255);
            emailAccount.Host = emailAccount.Host.Truncate(255);
            emailAccount.Username = emailAccount.Username.Truncate(255);
            emailAccount.Password = emailAccount.Password.Truncate(255);

            _emailAccountRepository.Insert(emailAccount);

            _cacheManager.RemoveByPattern(EMAILACCOUNT_PATTERN_KEY);
            _defaultEmailAccount = null;

            _eventPublisher.EntityInserted(emailAccount);
        }
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual int SendCampaign(Campaign campaign, EmailAccount emailAccount, IEnumerable<NewsLetterSubscription> subscriptions)
        {
            if (campaign == null)
                throw new ArgumentNullException("campaign");

            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

			if (subscriptions == null || subscriptions.Count() <= 0)
				return 0;

            int totalEmailsSent = 0;

			var subscriptionData = subscriptions
				.Where(x => _storeMappingService.Authorize<Campaign>(campaign, x.StoreId))
				.GroupBy(x => x.Email);

			foreach (var group in subscriptionData)
            {
				var subscription = group.First();	// only one email per email address

                var tokens = new List<Token>();
				_messageTokenProvider.AddStoreTokens(tokens, _storeContext.CurrentStore);
                _messageTokenProvider.AddNewsLetterSubscriptionTokens(tokens, subscription);

                var customer = _customerService.GetCustomerByEmail(subscription.Email);
                if (customer != null)
                    _messageTokenProvider.AddCustomerTokens(tokens, customer);

                string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
                string body = _tokenizer.Replace(campaign.Body, tokens, true);

                var email = new QueuedEmail()
                {
                    Priority = 3,
                    From = emailAccount.Email,
                    FromName = emailAccount.DisplayName,
                    To = subscription.Email,
                    Subject = subject,
                    Body = body,
                    CreatedOnUtc = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };

                _queuedEmailService.InsertQueuedEmail(email);
                totalEmailsSent++;
            }
            return totalEmailsSent;
        }
        public void Can_cascade_delete_attachment()
        {
            var account = new EmailAccount
            {
                Email = "*****@*****.**",
                Host = "127.0.0.1",
                Username = "******",
                Password = "******"
            };

            var download = new Download
            {
                ContentType = "text/plain",
                DownloadBinary = new byte[10],
                DownloadGuid = Guid.NewGuid(),
                Extension = "txt",
                Filename = "file"
            };

            // add attachment
            var attach = new QueuedEmailAttachment
            {
                StorageLocation = EmailAttachmentStorageLocation.FileReference,
                Name = "file.txt",
                MimeType = "text/plain",
                File = download
            };

            var qe = new QueuedEmail
            {
                Priority = 1,
                From = "From",
                To = "To",
                Subject = "Subject",
                CreatedOnUtc = DateTime.UtcNow,
                EmailAccount = account
            };

            qe.Attachments.Add(attach);

            var fromDb = SaveAndLoadEntity(qe);
            fromDb.ShouldNotBeNull();

            Assert.AreEqual(fromDb.Attachments.Count, 1);
            attach = fromDb.Attachments.FirstOrDefault();
            attach.ShouldNotBeNull();

            download = attach.File;
            download.ShouldNotBeNull();

            var attachId = attach.Id;
            var downloadId = download.Id;

            // delete Attachment.Download
            context.Set<Download>().Remove(download);
            context.SaveChanges();
            base.ReloadContext();

            attach = context.Set<QueuedEmailAttachment>().Find(attachId);
            attach.ShouldBeNull();

            // add new attachment
            attach = new QueuedEmailAttachment
            {
                StorageLocation = EmailAttachmentStorageLocation.FileReference,
                Name = "file.txt",
                MimeType = "text/plain"
            };

            qe = context.Set<QueuedEmail>().FirstOrDefault();
            qe.Attachments.Add(attach);

            fromDb = SaveAndLoadEntity(qe);
            fromDb.ShouldNotBeNull();

            // delete QueuedEmail
            context.Set<QueuedEmail>().Remove(fromDb);
            context.SaveChanges();
            base.ReloadContext();

            // Attachment should also be gone now
            attach = context.Set<QueuedEmailAttachment>().FirstOrDefault();
            attach.ShouldBeNull();
        }
        public int SendCampaign(Campaign campaign, EmailAccount emailAccount, IEnumerable<Account> accounts)
        {
            if (campaign == null)
                throw new ArgumentNullException("campaign");

            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            int totalEmailsSent = 0;

            foreach (var account in accounts)
            {
                var tokens = new List<Token>();
                _messageTokenProvider.AddWebTokens(tokens);
                if (account != null)
                    _messageTokenProvider.AddAccountTokens(tokens, account);

                string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
                string body = _tokenizer.Replace(campaign.Body, tokens, true);

                var email = new QueuedEmail()
                {
                    Priority = 3,
                    From = emailAccount.Email,
                    FromName = emailAccount.DisplayName,
                    To = account.Email,
                    Subject = subject,
                    Body = body,
                    CreatedOnUtc = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };
                _queuedEmailService.InsertQueuedEmail(email);
                totalEmailsSent++;
            }
            return totalEmailsSent;
        }
        /// <summary>
        /// Deletes an email account
        /// </summary>
        /// <param name="emailAccount">Email account</param>
        public virtual void DeleteEmailAccount(EmailAccount emailAccount)
        {
            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            if (GetAllEmailAccounts().Count == 1)
                throw new SmartException("You cannot delete this email account. At least one account is required.");

            _emailAccountRepository.Delete(emailAccount);

            //event notification
            _eventPublisher.EntityDeleted(emailAccount);
        }
Exemple #21
0
 /// <summary>
 /// Deletes an email account
 /// </summary>
 /// <param name="emailAccount">Email account</param>
 public void DeleteEmailAccount(EmailAccount emailAccount)
 {
     _emailAccountService.DeleteEmailAccount(emailAccount);
 }
Exemple #22
0
        private void LoadMoreData(string filePath)
        {
            List <EmailAccount> emailAccountList = new List <EmailAccount>();

            FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
            //根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档
            HSSFWorkbook workbook = new HSSFWorkbook(stream);
            //获取excel的第一个sheet
            HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);
            //最后一列的标号  即总的行数
            int rowCount = sheet.LastRowNum;

            for (int i = (sheet.FirstRowNum + 1); i < sheet.LastRowNum + 1; i++)
            {
                HSSFRow      row = (HSSFRow)sheet.GetRow(i);
                EmailAccount ea  = new EmailAccount();
                ea.EmailAccountID = Guid.NewGuid().ToString();
                if (row.GetCell(0) != null)
                {
                    ea.EmailAccountName = row.GetCell(0).ToString();
                }
                if (row.GetCell(1) != null)
                {
                    ea.EmailAccountAddress = row.GetCell(1).ToString();
                }
                if (row.GetCell(2) != null)
                {
                    ea.EmailAccountPassWord = row.GetCell(2).ToString();
                }
                if (row.GetCell(3) != null)
                {
                    ea.EmailAccountSMTP = row.GetCell(3).ToString();
                }
                if (row.GetCell(4) != null)
                {
                    ea.EmailAccountSMTPPort = int.Parse(row.GetCell(4).ToString());
                }
                if (row.GetCell(5) != null)
                {
                    ea.EmailAccountPOP3 = row.GetCell(5).ToString();
                }
                if (row.GetCell(6) != null)
                {
                    ea.EmailAccountPOP3Port = int.Parse(row.GetCell(6).ToString());
                }
                if (row.GetCell(7) != null)
                {
                    ea.EmailAccountIsSSL = row.GetCell(7).ToString() == "是" ? true : false;
                }
                if (row.GetCell(8) != null)
                {
                    ea.EmailAccountMaxEmailCount = int.Parse(row.GetCell(8).ToString());
                }
                if (row.GetCell(9) != null)
                {
                    ea.EmailAccountSpace = int.Parse(row.GetCell(9).ToString());
                }
                //if (row.GetCell(10) != null)
                //{
                //    if (row.GetCell(10).ToString() == "發送")
                //    {
                //        ea.SendMode = 0;
                //    }
                //    else
                //    {
                //        ea.SendMode = 1;
                //    }
                //}
                ea.SendMode = 1;//密送
                ea.EmailAccountCreateTime = DateTime.Now;
                ea.EmailAccountLastTime   = DateTime.Now;
                emailAccountList.Add(ea);
            }
            dgvSendEmail.DataSource = emailAccountList;
        }
Exemple #23
0
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual int SendCampaign(Campaign campaign, EmailAccount emailAccount,
                                        IEnumerable <NewsLetterSubscription> subscriptions, int languageId, List <int> Categories, DateTime startDate, DateTime?endDate, int itemCount)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            int  totalEmailsSent    = 0;
            bool hasProductsToken   = campaign.Body.IndexOf("%Store.RecentProducts%") > 0;
            bool hasBuyingRequests  = campaign.Body.IndexOf("%Store.RecentProductBuyingRequests%") > 0;
            var  productDates       = new NewsletterDates();
            var  buyingRequestDates = new NewsletterDates();
            var  tokens             = new List <Token>();

            if (hasProductsToken)
            {
                productDates = _newsletterDatesService.GetAllNewsletterDates().Where(x => x.LanguageId == languageId && x.IsProduct).FirstOrDefault();
                if (endDate == null)
                {
                    startDate = productDates.LastSubmit;
                }
                _messageTokenProvider.AddRecentProductsToken(tokens, languageId, Categories, startDate, endDate, itemCount);
            }
            if (hasBuyingRequests)
            {
                buyingRequestDates = _newsletterDatesService.GetAllNewsletterDates().Where(x => x.LanguageId == languageId && !x.IsProduct).FirstOrDefault();
                if (endDate == null)
                {
                    startDate = buyingRequestDates.LastSubmit;
                }
                _messageTokenProvider.AddRecentBuyingRequestsToken(tokens, languageId, Categories, startDate, endDate, itemCount);
            }

            foreach (var subscription in subscriptions.Where(x => x.LanguageId == languageId))
            {
                var tokensTemp = new List <Token>();
                tokensTemp.AddRange(tokens);
                _messageTokenProvider.AddStoreTokens(tokensTemp);
                _messageTokenProvider.AddNewsLetterSubscriptionTokens(tokensTemp, subscription);

                var customer = _customerService.GetCustomerByEmail(subscription.Email);
                if (customer != null)
                {
                    _messageTokenProvider.AddCustomerTokens(tokensTemp, customer);
                }

                string subject = _tokenizer.Replace(campaign.Subject, tokensTemp, false);
                string body    = _tokenizer.Replace(campaign.Body, tokensTemp, true);

                var email = new QueuedEmail()
                {
                    Priority       = 3,
                    From           = emailAccount.Email,
                    FromName       = emailAccount.DisplayName,
                    To             = subscription.Email,
                    Subject        = subject,
                    Body           = body,
                    CreatedOnUtc   = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };
                _queuedEmailService.InsertQueuedEmail(email);
                totalEmailsSent++;
            }
            if (hasProductsToken)
            {
                productDates.LastSubmit = DateTime.UtcNow;
                _newsletterDatesService.UpdateNewsletterDates(productDates);
            }
            if (hasBuyingRequests)
            {
                buyingRequestDates.LastSubmit = DateTime.UtcNow;
                _newsletterDatesService.UpdateNewsletterDates(buyingRequestDates);
            }

            return(totalEmailsSent);
        }
 public SmtpSendEmailChore(EmailAccount smtpSetting, EmailSettings sendEmailSetting) : base(sendEmailSetting, smtpSetting)
 {
     _smtpSetting = smtpSetting;
 }
Exemple #25
0
        /// <summary>
        /// Send email notification by message template
        /// </summary>
        /// <param name="messageTemplate">Message template</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="tokens">Tokens</param>
        /// <param name="toEmailAddress">Recipient email address</param>
        /// <param name="toName">Recipient name</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name</param>
        /// <param name="replyToEmailAddress">"Reply to" email</param>
        /// <param name="replyToName">"Reply to" name</param>
        /// <param name="fromEmail">Sender email. If specified, then it overrides passed "emailAccount" details</param>
        /// <param name="fromName">Sender name. If specified, then it overrides passed "emailAccount" details</param>
        /// <param name="subject">Subject. If specified, then it overrides subject of a message template</param>
        /// <returns>Queued email identifier</returns>
        private int?SendEmailNotification(MessageTemplate messageTemplate, EmailAccount emailAccount, IEnumerable <Token> tokens,
                                          string toEmailAddress, string toName,
                                          string attachmentFilePath  = null, string attachmentFileName = null,
                                          string replyToEmailAddress = null, string replyToName        = null,
                                          string fromEmail           = null, string fromName = null, string subject = null)
        {
            //get plugin settings
            var storeId            = (int?)tokens.FirstOrDefault(token => token.Key == "Store.Id")?.Value;
            var sendinBlueSettings = _settingService.LoadSetting <SendinBlueSettings>(storeId ?? 0);

            //ensure email notifications enabled
            if (!sendinBlueSettings.UseSmtp)
            {
                return(null);
            }

            //whether to send email by the passed message template
            var templateId = _genericAttributeService.GetAttribute <int?>(messageTemplate, SendinBlueDefaults.TemplateIdAttribute);
            var sendEmailForThisMessageTemplate = templateId.HasValue;

            if (!sendEmailForThisMessageTemplate)
            {
                return(null);
            }

            //get the specified email account from settings
            emailAccount = _emailAccountService.GetEmailAccountById(sendinBlueSettings.EmailAccountId) ?? emailAccount;

            //get an email from the template
            var email = _sendinBlueEmailManager.GetQueuedEmailFromTemplate(templateId.Value)
                        ?? throw new NopException($"There is no template with id {templateId}");

            //replace body and subject tokens
            if (string.IsNullOrEmpty(subject))
            {
                subject = email.Subject;
            }
            if (!string.IsNullOrEmpty(subject))
            {
                email.Subject = _tokenizer.Replace(subject, tokens, false);
            }
            if (!string.IsNullOrEmpty(email.Body))
            {
                email.Body = _tokenizer.Replace(email.Body, tokens, true);
            }

            //set email parameters
            email.Priority              = QueuedEmailPriority.High;
            email.From                  = !string.IsNullOrEmpty(fromEmail) ? fromEmail : email.From;
            email.FromName              = !string.IsNullOrEmpty(fromName) ? fromName : email.FromName;
            email.To                    = toEmailAddress;
            email.ToName                = CommonHelper.EnsureMaximumLength(toName, 300);
            email.ReplyTo               = replyToEmailAddress;
            email.ReplyToName           = replyToName;
            email.CC                    = string.Empty;
            email.Bcc                   = messageTemplate.BccEmailAddresses;
            email.AttachmentFilePath    = attachmentFilePath;
            email.AttachmentFileName    = attachmentFileName;
            email.AttachedDownloadId    = messageTemplate.AttachedDownloadId;
            email.CreatedOnUtc          = DateTime.UtcNow;
            email.EmailAccountId        = emailAccount.Id;
            email.DontSendBeforeDateUtc = messageTemplate.DelayBeforeSend.HasValue
                ? (DateTime?)(DateTime.UtcNow + TimeSpan.FromHours(messageTemplate.DelayPeriod.ToHours(messageTemplate.DelayBeforeSend.Value)))
                : null;

            //queue email
            _queuedEmailService.InsertQueuedEmail(email);
            return(email.Id);
        }
        /// <summary>
        /// Updates an email account
        /// </summary>
        /// <param name="emailAccount">Email account</param>
        public virtual void UpdateEmailAccount(EmailAccount emailAccount)
        {
            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            emailAccount.Email = CommonHelper.EnsureNotNull(emailAccount.Email);
            emailAccount.DisplayName = CommonHelper.EnsureNotNull(emailAccount.DisplayName);
            emailAccount.Host = CommonHelper.EnsureNotNull(emailAccount.Host);
            emailAccount.Username = CommonHelper.EnsureNotNull(emailAccount.Username);
            emailAccount.Password = CommonHelper.EnsureNotNull(emailAccount.Password);

            emailAccount.Email = emailAccount.Email.Trim();
            emailAccount.DisplayName = emailAccount.DisplayName.Trim();
            emailAccount.Host = emailAccount.Host.Trim();
            emailAccount.Username = emailAccount.Username.Trim();
            emailAccount.Password = emailAccount.Password.Trim();

            emailAccount.Email = CommonHelper.EnsureMaximumLength(emailAccount.Email, 255);
            emailAccount.DisplayName = CommonHelper.EnsureMaximumLength(emailAccount.DisplayName, 255);
            emailAccount.Host = CommonHelper.EnsureMaximumLength(emailAccount.Host, 255);
            emailAccount.Username = CommonHelper.EnsureMaximumLength(emailAccount.Username, 255);
            emailAccount.Password = CommonHelper.EnsureMaximumLength(emailAccount.Password, 255);

            _emailAccountRepository.Update(emailAccount);
        }
Exemple #27
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="fromAddress">From address</param>
        /// <param name="fromName">From display name</param>
        /// <param name="toAddress">To address</param>
        /// <param name="toName">To display name</param>
        /// <param name="replyToAddress">ReplyTo address</param>
        /// <param name="replyToName">ReplyTo display name</param>
        /// <param name="bccAddresses">BCC addresses list</param>
        /// <param name="ccAddresses">CC addresses list</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>
        /// <param name="attachedDownloads">Attachment download ID (another attachedment)</param>
        public virtual async Task SendEmail(EmailAccount emailAccount, string subject, string body,
                                            string fromAddress, string fromName, string toAddress, string toName,
                                            string replyToAddress                  = null, string replyToName = null,
                                            IEnumerable <string> bccAddresses      = null, IEnumerable <string> ccAddresses = null,
                                            string attachmentFilePath              = null, string attachmentFileName = null,
                                            IEnumerable <string> attachedDownloads = null)

        {
            var message = new MimeMessage();

            //from, to, reply to
            message.From.Add(new MailboxAddress(fromName, fromAddress));
            message.To.Add(new MailboxAddress(toName, toAddress));
            if (!String.IsNullOrEmpty(replyToAddress))
            {
                message.ReplyTo.Add(new MailboxAddress(replyToName, replyToAddress));
            }

            //BCC
            if (bccAddresses != null && bccAddresses.Any())
            {
                foreach (var address in bccAddresses.Where(bccValue => !String.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(MailboxAddress.Parse(address.Trim()));
                }
            }

            //CC
            if (ccAddresses != null && ccAddresses.Any())
            {
                foreach (var address in ccAddresses.Where(ccValue => !String.IsNullOrWhiteSpace(ccValue)))
                {
                    message.Cc.Add(MailboxAddress.Parse(address.Trim()));
                }
            }

            //subject
            message.Subject = subject;

            //content
            var builder = new BodyBuilder();

            builder.HtmlBody = body;

            //create  the file attachment for this e-mail message
            if (!String.IsNullOrEmpty(attachmentFilePath) &&
                File.Exists(attachmentFilePath))
            {
                // TODO: should probably include a check for the attachmentFileName not being null or white space
                var attachment = new MimePart(_mimeMappingService.Map(attachmentFileName))
                {
                    Content            = new MimeContent(File.OpenRead(attachmentFilePath), ContentEncoding.Default),
                    ContentDisposition = new ContentDisposition(ContentDisposition.Attachment)
                    {
                        CreationDate     = File.GetCreationTime(attachmentFilePath),
                        ModificationDate = File.GetLastWriteTime(attachmentFilePath),
                        ReadDate         = File.GetLastAccessTime(attachmentFilePath)
                    },
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName = Path.GetFileName(attachmentFilePath),
                };
                builder.Attachments.Add(attachment);
            }
            //another attachment?
            if (attachedDownloads != null)
            {
                foreach (var attachedDownloadId in attachedDownloads)
                {
                    var download = await _downloadService.GetDownloadById(attachedDownloadId);

                    if (download != null)
                    {
                        //we do not support URLs as attachments
                        if (!download.UseDownloadUrl)
                        {
                            string fileName = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id;
                            fileName += download.Extension;
                            var ms         = new MemoryStream(download.DownloadBinary);
                            var attachment = new MimePart(download.ContentType ?? _mimeMappingService.Map(fileName))
                            {
                                Content            = new MimeContent(ms, ContentEncoding.Default),
                                ContentDisposition = new ContentDisposition(ContentDisposition.Attachment)
                                {
                                    CreationDate     = DateTime.UtcNow,
                                    ModificationDate = DateTime.UtcNow,
                                    ReadDate         = DateTime.UtcNow
                                },
                                ContentTransferEncoding = ContentEncoding.Base64,
                                FileName = fileName,
                            };
                            builder.Attachments.Add(attachment);
                        }
                    }
                }
            }
            message.Body = builder.ToMessageBody();

            //send email
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => emailAccount.UseServerCertificateValidation;
                await smtpClient.ConnectAsync(emailAccount.Host, emailAccount.Port, (SecureSocketOptions)emailAccount.SecureSocketOptionsId);

                await smtpClient.AuthenticateAsync(emailAccount.Username, emailAccount.Password);

                await smtpClient.SendAsync(message);

                await smtpClient.DisconnectAsync(true);
            }
        }
Exemple #28
0
        public void NewPop3EmailAccount()
        {
            var emailAccount = new EmailAccount();

            EditEmailAccountControllerRun(EditPop3EmailAccountDialog, emailAccount);
        }
Exemple #29
0
 public bool setAccount(string sMailAccount)
 {
     session.Dispose();
     session = new OutlookSession();
     //eMail = new EmailMessage();
     bool bFound = false;
     foreach (Account acc in session.EmailAccounts)
     {
         if (acc.Name == sMailAccount)
         {
             account = session.EmailAccounts[sMailAccount];
             bFound = true;
         }
     }
     return bFound;
 }
        public async Task AddStoreTokens(LiquidObject liquidObject, Store store, Language language, EmailAccount emailAccount)
        {
            var liquidStore = new LiquidStore(store, language, emailAccount);

            liquidStore.TwitterLink   = _storeInformationSettings.TwitterLink;
            liquidStore.FacebookLink  = _storeInformationSettings.FacebookLink;
            liquidStore.YoutubeLink   = _storeInformationSettings.YoutubeLink;
            liquidStore.InstagramLink = _storeInformationSettings.InstagramLink;
            liquidStore.LinkedInLink  = _storeInformationSettings.LinkedInLink;
            liquidStore.PinterestLink = _storeInformationSettings.PinterestLink;

            liquidObject.Store = liquidStore;

            await _mediator.EntityTokensAdded(store, liquidStore, liquidObject);
        }
 public void GetUserEmails(EmailAccount currentAccount)
 {
     inboxManager.StartGettinMessages(currentAccount);
 }
Exemple #32
0
 public static EmailAccount ToEntity(this EmailAccountModel model, EmailAccount destination)
 {
     return(Mapper.Map(model, destination));
 }
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual async Task <int> SendCampaign(Campaign campaign, EmailAccount emailAccount,
                                                     IEnumerable <NewsLetterSubscription> subscriptions)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            int totalEmailsSent = 0;
            var language        = _serviceProvider.GetRequiredService <IWorkContext>().WorkingLanguage;

            foreach (var subscription in subscriptions)
            {
                Customer customer = null;

                if (!String.IsNullOrEmpty(subscription.CustomerId))
                {
                    customer = await _customerService.GetCustomerById(subscription.CustomerId);
                }

                if (customer == null)
                {
                    customer = await _customerService.GetCustomerByEmail(subscription.Email);
                }

                //ignore deleted or inactive customers when sending newsletter campaigns
                if (customer != null && (!customer.Active || customer.Deleted))
                {
                    continue;
                }

                LiquidObject liquidObject = new LiquidObject();
                await _messageTokenProvider.AddStoreTokens(liquidObject, _storeContext.CurrentStore, language, emailAccount);

                await _messageTokenProvider.AddNewsLetterSubscriptionTokens(liquidObject, subscription, _storeContext.CurrentStore);

                if (customer != null)
                {
                    await _messageTokenProvider.AddCustomerTokens(liquidObject, customer, _storeContext.CurrentStore, language);

                    await _messageTokenProvider.AddShoppingCartTokens(liquidObject, customer, _storeContext.CurrentStore, language);
                }

                var body    = LiquidExtensions.Render(liquidObject, campaign.Body);
                var subject = LiquidExtensions.Render(liquidObject, campaign.Subject);

                var email = new QueuedEmail
                {
                    Priority       = QueuedEmailPriority.Low,
                    From           = emailAccount.Email,
                    FromName       = emailAccount.DisplayName,
                    To             = subscription.Email,
                    Subject        = subject,
                    Body           = body,
                    CreatedOnUtc   = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };
                await _queuedEmailService.InsertQueuedEmail(email);
                await InsertCampaignHistory(new CampaignHistory()
                {
                    CampaignId = campaign.Id, CustomerId = subscription.CustomerId, Email = subscription.Email, CreatedDateUtc = DateTime.UtcNow, StoreId = campaign.StoreId
                });

                //activity log
                if (customer != null)
                {
                    await _customerActivityService.InsertActivity("CustomerReminder.SendCampaign", campaign.Id, _localizationService.GetResource("ActivityLog.SendCampaign"), customer, campaign.Name);
                }
                else
                {
                    await _customerActivityService.InsertActivity("CustomerReminder.SendCampaign", campaign.Id, _localizationService.GetResource("ActivityLog.SendCampaign"), campaign.Name + " - " + subscription.Email);
                }

                totalEmailsSent++;
            }
            return(totalEmailsSent);
        }
Exemple #34
0
 public static EmailAccountModel ToModel(this EmailAccount entity)
 {
     return(entity.MapTo <EmailAccount, EmailAccountModel>());
 }
Exemple #35
0
        public void NewExchangeEmailAccount()
        {
            var emailAccount = new EmailAccount();

            EditEmailAccountControllerRun(EditExchangeEmailAccountDialog, emailAccount);
        }
Exemple #36
0
 /// <summary>
 /// Updates an email account
 /// </summary>
 /// <param name="emailAccount">Email account</param>
 public void UpdateEmailAccount(EmailAccount emailAccount)
 {
     _emailAccountService.UpdateEmailAccount(emailAccount);
 }
Exemple #37
0
 public void SendEmail(EmailAccount emailAccount, string subject, string body, string fromAddress, string fromName, string toAddress, string toName, IEnumerable<string> bcc = null, IEnumerable<string> cc = null)
 {
     SendEmail(emailAccount, subject, body,
         new MailAddress(fromAddress, fromName), new MailAddress(toAddress, toName),
         bcc, cc);
 }
Exemple #38
0
        private void EditEmailAccountControllerRun(Action <MockEditEmailAccountView> showDialogAction, EmailAccount emailAccount)
        {
            var ownerWindow = new object();
            var controller  = Container.GetExportedValue <EditEmailAccountController>();

            controller.OwnerWindow  = ownerWindow;
            controller.EmailAccount = emailAccount;
            controller.Initialize();

            bool showDialogCalled = false;

            MockEditEmailAccountView.ShowDialogAction = v =>
            {
                showDialogCalled = true;
                showDialogAction(v);
            };
            controller.Run();
            Assert.IsTrue(showDialogCalled);

            MockEditEmailAccountView.ShowDialogAction = null;
        }
Exemple #39
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="fromAddress">From address</param>
        /// <param name="fromName">From display name</param>
        /// <param name="toAddress">To address</param>
        /// <param name="toName">To display name</param>
        /// <param name="replyTo">ReplyTo address</param>
        /// <param name="replyToName">ReplyTo display name</param>
        /// <param name="bcc">BCC addresses list</param>
        /// <param name="cc">CC addresses list</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>
        public void SendEmail(EmailAccount emailAccount, string subject, string body,
                              string fromAddress, string fromName, string toAddress, string toName,
                              string replyTo            = null, string replyToName = null,
                              IEnumerable <string> bcc  = null, IEnumerable <string> cc   = null,
                              string attachmentFilePath = null, string attachmentFileName = null)
        {
            var message = new MailMessage();

            //from, to, reply to
            message.From = new MailAddress(fromAddress, fromName);
            message.To.Add(new MailAddress(toAddress, toName));
            if (!String.IsNullOrEmpty(replyTo))
            {
                message.ReplyToList.Add(new MailAddress(replyTo, replyToName));
            }

            //BCC
            if (bcc != null)
            {
                foreach (var address in bcc.Where(bccValue => !String.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(address.Trim());
                }
            }

            //CC
            if (cc != null)
            {
                foreach (var address in cc.Where(ccValue => !String.IsNullOrWhiteSpace(ccValue)))
                {
                    message.CC.Add(address.Trim());
                }
            }

            //content
            message.Subject    = subject;
            message.Body       = body;
            message.IsBodyHtml = true;

            //create  the file attachment for this e-mail message
            if (!String.IsNullOrEmpty(attachmentFilePath) &&
                File.Exists(attachmentFilePath))
            {
                var attachment = new Attachment(attachmentFilePath);
                attachment.ContentDisposition.CreationDate     = File.GetCreationTime(attachmentFilePath);
                attachment.ContentDisposition.ModificationDate = File.GetLastWriteTime(attachmentFilePath);
                attachment.ContentDisposition.ReadDate         = File.GetLastAccessTime(attachmentFilePath);
                if (!String.IsNullOrEmpty(attachmentFileName))
                {
                    attachment.Name = attachmentFileName;
                }
                message.Attachments.Add(attachment);
            }

            //send email
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host      = emailAccount.Host;
                smtpClient.Port      = emailAccount.Port;
                smtpClient.EnableSsl = emailAccount.EnableSsl;
                if (emailAccount.UseDefaultCredentials)
                {
                    smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    smtpClient.Credentials = new NetworkCredential(emailAccount.Username, emailAccount.Password);
                }
                smtpClient.Send(message);
            }
        }
Exemple #40
0
        public Task SendEmailAsync(EmailAccount emailAccount, string subject, string body,
                                   string fromAddress, string fromName, string toAddress, string toName,
                                   string replyTo                       = null, string replyToName = null, string attachmentFilePath = null, string attachmentFileName = null,
                                   IEnumerable <string> bcc             = null, IEnumerable <string> cc = null,
                                   IDictionary <string, string> headers = null)
        {
            MailMessage message = new MailMessage
            {
                //from, to, reply to
                From = new MailAddress(fromAddress, fromName)
            };

            message.To.Add(new MailAddress(toAddress, toName));
            if (!string.IsNullOrEmpty(replyTo))
            {
                message.ReplyToList.Add(new MailAddress(replyTo, replyToName));
            }

            //BCC
            if (bcc != null)
            {
                foreach (string address in bcc.Where(bccValue => !string.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(address.Trim());
                }
            }

            //CC
            if (cc != null)
            {
                foreach (string address in cc.Where(ccValue => !string.IsNullOrWhiteSpace(ccValue)))
                {
                    message.CC.Add(address.Trim());
                }
            }

            //content
            message.Subject    = subject;
            message.Body       = body;
            message.IsBodyHtml = true;

            //headers
            if (headers != null)
            {
                foreach (KeyValuePair <string, string> header in headers)
                {
                    message.Headers.Add(header.Key, header.Value);
                }
            }

            //create the file attachment for this e-mail message
            if (!string.IsNullOrEmpty(attachmentFilePath) &&
                _fileProvider.FileExists(attachmentFilePath))
            {
                Attachment attachment = new Attachment(attachmentFilePath);
                attachment.ContentDisposition.CreationDate     = _fileProvider.GetCreationTime(attachmentFilePath);
                attachment.ContentDisposition.ModificationDate = _fileProvider.GetLastWriteTime(attachmentFilePath);
                attachment.ContentDisposition.ReadDate         = _fileProvider.GetLastAccessTime(attachmentFilePath);
                if (!string.IsNullOrEmpty(attachmentFileName))
                {
                    attachment.Name = attachmentFileName;
                }

                message.Attachments.Add(attachment);
            }


            //send email
            using (SmtpClient smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host        = emailAccount.Host;
                smtpClient.Port        = emailAccount.Port;
                smtpClient.EnableSsl   = emailAccount.EnableSsl;
                smtpClient.Credentials = emailAccount.UseDefaultCredentials ?
                                         CredentialCache.DefaultNetworkCredentials :
                                         new NetworkCredential(emailAccount.Username, emailAccount.Password);
                smtpClient.Send(message);
            }

            return(Task.CompletedTask);
        }
Exemple #41
0
    public void SendNewEmail()
    {
        var root         = new EmailClientRoot();
        var emailAccount = new EmailAccount()
        {
            Email = "*****@*****.**"
        };

        root.AddEmailAccount(emailAccount);

        var controller = Get <NewEmailController>();

        controller.Root = root;
        controller.Initialize();

        // Create a new email

        var newEmailViewModel = controller.NewEmailViewModel;
        var newEmailView      = (MockNewEmailView)newEmailViewModel.View;

        controller.Run();

        Assert.IsTrue(newEmailView.IsVisible);
        Assert.AreEqual(emailAccount, newEmailViewModel.SelectedEmailAccount);

        // Select a contact for the To field and cancel the dialog

        var        addressBookService = Get <MockAddressBookService>();
        ContactDto?contactResult      = null;

        addressBookService.ShowSelectContactViewAction = owner =>
        {
            Assert.AreEqual(newEmailView, owner);
            return(contactResult);
        };

        newEmailViewModel.SelectContactCommand.Execute("To");

        // Select a contact for the To field

        contactResult = new ContactDto("", "", "*****@*****.**");
        newEmailViewModel.SelectContactCommand.Execute("To");
        Assert.AreEqual("*****@*****.**", newEmailViewModel.To);

        // Select a contact for the CC field

        contactResult = new ContactDto("", "", "*****@*****.**");
        newEmailViewModel.SelectContactCommand.Execute("CC");
        Assert.AreEqual("*****@*****.**", newEmailViewModel.CC);

        // Select a contact for the BCC field

        contactResult = new ContactDto("", "", "*****@*****.**");
        newEmailViewModel.SelectContactCommand.Execute("Bcc");
        Assert.AreEqual("*****@*****.**", newEmailViewModel.Bcc);

        // Pass a wrong parameter to the command => exception

        AssertHelper.ExpectedException <ArgumentException>(() => newEmailViewModel.SelectContactCommand.Execute("Wrong field"));

        // Send the email

        newEmailViewModel.SendCommand.Execute(null);

        var sendEmail = root.Sent.Emails.Single();

        Assert.AreEqual("*****@*****.**", sendEmail.From);
        Assert.AreNotEqual(new DateTime(0), sendEmail.Sent);

        Assert.IsFalse(newEmailView.IsVisible);
    }
        /// <summary>
        /// Send notification
        /// </summary>
        /// <param name="messageTemplate">Message template</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="languageId">Language identifier</param>
        /// <param name="tokens">Tokens</param>
        /// <param name="toEmailAddress">Recipient email address</param>
        /// <param name="toName">Recipient name</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name</param>
        /// <param name="replyToEmailAddress">"Reply to" email</param>
        /// <param name="replyToName">"Reply to" name</param>
        /// <param name="fromEmail">Sender email. If specified, then it overrides passed "emailAccount" details</param>
        /// <param name="fromName">Sender name. If specified, then it overrides passed "emailAccount" details</param>
        /// <param name="subject">Subject. If specified, then it overrides subject of a message template</param>
        /// <returns>Queued email identifier</returns>
        protected override async Task <int> SendNotificationAsync(MessageTemplate messageTemplate, EmailAccount emailAccount, int languageId, IList <Token> tokens,
                                                                  string toEmailAddress, string toName, string attachmentFilePath = null, string attachmentFileName = null,
                                                                  string replyToEmailAddress = null, string replyToName = null, string fromEmail = null, string fromName = null,
                                                                  string subject             = null)
        {
            if (messageTemplate == null)
            {
                throw new ArgumentNullException(nameof(messageTemplate));
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException(nameof(emailAccount));
            }

            //try to send SMS notification
            await SendSmsNotificationAsync(messageTemplate, tokens);

            //try to send email notification
            var emailId = await SendEmailNotificationAsync(messageTemplate, emailAccount, tokens,
                                                           toEmailAddress, toName, attachmentFilePath, attachmentFileName,
                                                           replyToEmailAddress, replyToName, fromEmail, fromName, subject);

            if (emailId.HasValue)
            {
                return(emailId.Value);
            }

            //send base notification
            return(await base.SendNotificationAsync(messageTemplate, emailAccount, languageId, tokens,
                                                    toEmailAddress, toName, attachmentFilePath, attachmentFileName,
                                                    replyToEmailAddress, replyToName, fromEmail, fromName, subject));
        }
Exemple #43
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="fromAddress">From address</param>
        /// <param name="fromName">From display name</param>
        /// <param name="toAddress">To address</param>
        /// <param name="toName">To display name</param>
        /// <param name="replyTo">ReplyTo address</param>
        /// <param name="replyToName">ReplyTo display name</param>
        /// <param name="bcc">BCC addresses list</param>
        /// <param name="cc">CC addresses list</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>
        /// <param name="attachedDownloadId">Attachment download ID (another attachedment)</param>
        /// <param name="headers">Headers</param>
        public virtual void SendEmail(EmailAccount emailAccount, string subject, string body,
                                      string fromAddress, string fromName, string toAddress, string toName,
                                      string replyTo            = null, string replyToName = null,
                                      IEnumerable <string> bcc  = null, IEnumerable <string> cc           = null,
                                      string attachmentFilePath = null, string attachmentFileName         = null,
                                      int attachedDownloadId    = 0, IDictionary <string, string> headers = null)
        {
            var message = new MailMessage
            {
                //from, to, reply to
                From = new MailAddress(fromAddress, fromName)
            };

            message.To.Add(new MailAddress(toAddress, toName));
            if (!string.IsNullOrEmpty(replyTo))
            {
                message.ReplyToList.Add(new MailAddress(replyTo, replyToName));
            }

            //BCC
            if (bcc != null)
            {
                foreach (var address in bcc.Where(bccValue => !string.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(address.Trim());
                }
            }

            //CC
            if (cc != null)
            {
                foreach (var address in cc.Where(ccValue => !string.IsNullOrWhiteSpace(ccValue)))
                {
                    message.CC.Add(address.Trim());
                }
            }

            //content
            message.Subject    = subject;
            message.Body       = body;
            message.IsBodyHtml = true;

            //headers
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    message.Headers.Add(header.Key, header.Value);
                }
            }

            //create the file attachment for this e-mail message
            if (!string.IsNullOrEmpty(attachmentFilePath) &&
                _fileProvider.FileExists(attachmentFilePath))
            {
                var attachment = new Attachment(attachmentFilePath);
                attachment.ContentDisposition.CreationDate     = _fileProvider.GetCreationTime(attachmentFilePath);
                attachment.ContentDisposition.ModificationDate = _fileProvider.GetLastWriteTime(attachmentFilePath);
                attachment.ContentDisposition.ReadDate         = _fileProvider.GetLastAccessTime(attachmentFilePath);
                if (!string.IsNullOrEmpty(attachmentFileName))
                {
                    attachment.Name = attachmentFileName;
                }
                message.Attachments.Add(attachment);
            }
            //another attachment?
            if (attachedDownloadId > 0)
            {
                var download = _downloadService.GetDownloadById(attachedDownloadId);
                if (download != null)
                {
                    //we do not support URLs as attachments
                    if (!download.UseDownloadUrl)
                    {
                        var fileName = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id.ToString();
                        fileName += download.Extension;


                        var ms         = new MemoryStream(download.DownloadBinary);
                        var attachment = new Attachment(ms, fileName);
                        //string contentType = !string.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream";
                        //var attachment = new Attachment(ms, fileName, contentType);
                        attachment.ContentDisposition.CreationDate     = DateTime.UtcNow;
                        attachment.ContentDisposition.ModificationDate = DateTime.UtcNow;
                        attachment.ContentDisposition.ReadDate         = DateTime.UtcNow;
                        message.Attachments.Add(attachment);
                    }
                }
            }

            //send email
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host        = emailAccount.Host;
                smtpClient.Port        = emailAccount.Port;
                smtpClient.EnableSsl   = emailAccount.EnableSsl;
                smtpClient.Credentials = emailAccount.UseDefaultCredentials ?
                                         CredentialCache.DefaultNetworkCredentials :
                                         new NetworkCredential(emailAccount.Username, emailAccount.Password);
                smtpClient.Send(message);
            }
        }
        protected EmailAccount Save()
        {
            EmailAccount emailAccount = ctrlEmailAccountInfo.SaveInfo();

            return(emailAccount);
        }
Exemple #45
0
        public override void HandleAutoTask()
        {
            LogManager.Instance.Write("Start Email Handler ******************************************************");

            var emailAccount = new EmailAccount()
            {
                Email                 = ConfigurationManager.AppSettings["EmailAccount"],
                DisplayName           = ConfigurationManager.AppSettings["EmailDisplayName"],
                Host                  = ConfigurationManager.AppSettings["EmailHost"],
                Port                  = int.Parse(ConfigurationManager.AppSettings["EmailPort"]),
                Username              = ConfigurationManager.AppSettings["EmailUsername"],
                Password              = ConfigurationManager.AppSettings["EmailPassword"],
                EnableSsl             = bool.Parse(ConfigurationManager.AppSettings["EmailEnableSsl"]),
                UseDefaultCredentials = bool.Parse(ConfigurationManager.AppSettings["EmailUseDefaultCredentials"]),
            };

            using (var cache = new EntityCache <Email, CHCContext>(p => !p.SentDate.HasValue))
            {
                while (true)
                {
                    LogManager.Instance.Write(cache.Results.Count().ToString());

                    if (cache.Results.Count() > 0)
                    {
                        foreach (var email in cache.Results)
                        {
                            var bcc = String.IsNullOrWhiteSpace(email.Bcc)
                                        ? null
                                        : email.Bcc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                            var cc = String.IsNullOrWhiteSpace(email.CC)
                                        ? null
                                        : email.CC.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                            try
                            {
                                EmailHelper.SendEmail(emailAccount, email.Subject, email.Body, emailAccount.Email, emailAccount.DisplayName, email.To, email.ToName,
                                                      email.ReplyTo, email.ReplyToName, bcc, cc, email.AttachmentFilePath, email.AttachmentFileName);

                                using (var context = new CHCContext())
                                {
                                    var entity = context.Email.SingleOrDefault(e => e.Id == email.Id);
                                    entity.SentTries++;
                                    entity.SentDate = DateTime.Now;
                                    context.SaveChanges();
                                }
                            }
                            catch (Exception ex)
                            {
                                LogManager.Instance.Write(ex.ToString());
                                using (var context = new CHCContext())
                                {
                                    var entity = context.Email.SingleOrDefault(e => e.Id == email.Id);
                                    entity.SentTries++;
                                    context.SaveChanges();
                                }
                            }
                        }
                    }

                    Thread.Sleep(5000);
                }
            }
        }
Exemple #46
0
 public GmailController(EmailAccount emailAccount)
 {
     _emailAccount = emailAccount;
 }
Exemple #47
0
 public static EmailAccountModel ToModel(this EmailAccount entity)
 {
     return(Mapper.Map <EmailAccount, EmailAccountModel>(entity));
 }
Exemple #48
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="fromAddress">From address</param>
        /// <param name="fromName">From display name</param>
        /// <param name="toAddress">To address</param>
        /// <param name="toName">To display name</param>
        /// <param name="replyTo">ReplyTo address</param>
        /// <param name="replyToName">ReplyTo display name</param>
        /// <param name="bcc">BCC addresses list</param>
        /// <param name="cc">CC addresses list</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>
        /// <param name="attachedDownloadId">Attachment download ID (another attachment)</param>
        /// <param name="headers">Headers</param>
        public virtual async Task SendEmailAsync(EmailAccount emailAccount, string subject, string body,
                                                 string fromAddress, string fromName, string toAddress, string toName,
                                                 string replyTo            = null, string replyToName = null,
                                                 IEnumerable <string> bcc  = null, IEnumerable <string> cc           = null,
                                                 string attachmentFilePath = null, string attachmentFileName         = null,
                                                 int attachedDownloadId    = 0, IDictionary <string, string> headers = null)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(fromName, fromAddress));
            message.To.Add(new MailboxAddress(toName, toAddress));

            if (!string.IsNullOrEmpty(replyTo))
            {
                message.ReplyTo.Add(new MailboxAddress(replyToName, replyTo));
            }

            //BCC
            if (bcc != null)
            {
                foreach (var address in bcc.Where(bccValue => !string.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(new MailboxAddress("", address.Trim()));
                }
            }

            //CC
            if (cc != null)
            {
                foreach (var address in cc.Where(ccValue => !string.IsNullOrWhiteSpace(ccValue)))
                {
                    message.Cc.Add(new MailboxAddress("", address.Trim()));
                }
            }

            //content
            message.Subject = subject;

            //headers
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    message.Headers.Add(header.Key, header.Value);
                }
            }

            var multipart = new Multipart("mixed")
            {
                new TextPart(TextFormat.Html)
                {
                    Text = body
                }
            };

            //create the file attachment for this e-mail message
            if (!string.IsNullOrEmpty(attachmentFilePath) && _fileProvider.FileExists(attachmentFilePath))
            {
                multipart.Add(await CreateMimeAttachmentAsync(attachmentFilePath, attachmentFileName));
            }

            //another attachment?
            if (attachedDownloadId > 0)
            {
                var download = await _downloadService.GetDownloadByIdAsync(attachedDownloadId);

                //we do not support URLs as attachments
                if (!download?.UseDownloadUrl ?? false)
                {
                    multipart.Add(CreateMimeAttachment(download));
                }
            }

            message.Body = multipart;

            //send email
            using var smtpClient = await _smtpBuilder.BuildAsync(emailAccount);

            await smtpClient.SendAsync(message);

            await smtpClient.DisconnectAsync(true);
        }
Exemple #49
0
        public void Can_cascade_delete_attachment()
        {
            var account = new EmailAccount
            {
                Email    = "*****@*****.**",
                Host     = "127.0.0.1",
                Username = "******",
                Password = "******"
            };

            var download = new Download
            {
                ContentType  = "text/plain",
                MediaStorage = new MediaStorage
                {
                    Data = new byte[10]
                },
                UpdatedOnUtc = DateTime.UtcNow,
                DownloadGuid = Guid.NewGuid(),
                Extension    = "txt",
                Filename     = "file"
            };

            // add attachment
            var attach = new QueuedEmailAttachment
            {
                StorageLocation = EmailAttachmentStorageLocation.FileReference,
                Name            = "file.txt",
                MimeType        = "text/plain",
                File            = download
            };

            var qe = new QueuedEmail
            {
                Priority     = 1,
                From         = "From",
                To           = "To",
                Subject      = "Subject",
                CreatedOnUtc = DateTime.UtcNow,
                EmailAccount = account
            };

            qe.Attachments.Add(attach);

            var fromDb = SaveAndLoadEntity(qe);

            fromDb.ShouldNotBeNull();

            Assert.AreEqual(fromDb.Attachments.Count, 1);
            attach = fromDb.Attachments.FirstOrDefault();
            attach.ShouldNotBeNull();

            download = attach.File;
            download.ShouldNotBeNull();

            var attachId   = attach.Id;
            var downloadId = download.Id;

            // delete Attachment.Download
            context.Set <Download>().Remove(download);
            context.SaveChanges();
            base.ReloadContext();

            attach = context.Set <QueuedEmailAttachment>().Find(attachId);
            attach.ShouldBeNull();

            // add new attachment
            attach = new QueuedEmailAttachment
            {
                StorageLocation = EmailAttachmentStorageLocation.FileReference,
                Name            = "file.txt",
                MimeType        = "text/plain"
            };

            qe = context.Set <QueuedEmail>().FirstOrDefault();
            qe.Attachments.Add(attach);

            fromDb = SaveAndLoadEntity(qe);
            fromDb.ShouldNotBeNull();

            // delete QueuedEmail
            context.Set <QueuedEmail>().Remove(fromDb);
            context.SaveChanges();
            base.ReloadContext();

            // Attachment should also be gone now
            attach = context.Set <QueuedEmailAttachment>().FirstOrDefault();
            attach.ShouldBeNull();
        }
Exemple #50
0
        private void frmMain_Load(object sender, EventArgs e)
        {
            //set default refresh delay
            watch.Delay = (int)numDelay.Value * 1000;

            //setup events for lst server
            lstServer.DrawItem += lstServer_DrawItem;
            lstServer.DrawMode  = DrawMode.OwnerDrawFixed;

            //setup events for draw email
            lstEmail.DrawItem += lstEmail_DrawItem;
            lstEmail.DrawMode  = DrawMode.OwnerDrawFixed;


            //check for settings file
            if (File.Exists("Settings.dat"))
            {
                //create memory stream of settings information
                using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(File.ReadAllText("Settings.dat"))))
                {
                    //read the settings as binary information
                    using (BinaryReader br = new BinaryReader(ms))
                    {
                        //read delay settings
                        watch.Delay    = br.ReadInt32();
                        numDelay.Value = watch.Delay / 1000;

                        //determine amount of email accounts to notify
                        int count = br.ReadInt32();
                        for (int i = 0; i < count; i++)
                        {
                            //load each email account
                            EmailAccount m = new EmailAccount();
                            m.Address     = br.ReadString();
                            m.Password    = br.ReadString();
                            m.SMTP_INDEX  = br.ReadInt32();
                            m.SMTP_SERVER = br.ReadString();
                            m.SMTP_PORT   = br.ReadInt32();
                            watch.Emails.Add(m);
                            lstEmail.Items.Add(m.Address);
                        }

                        //determine the amount of servers
                        count = br.ReadInt32();
                        for (int i = 0; i < count; i++)
                        {
                            //load each server
                            Server s = new Server();
                            s.IP   = br.ReadString();
                            s.PORT = br.ReadInt32();

                            watch.WatchList.Add(s);
                            lstServer.Items.Add(s.IP + ":" + s.PORT);
                        }
                    }
                }
            }

            //add event for form close
            this.FormClosing += frmMain_FormClosing;
        }
Exemple #51
0
 public static EmailAccount ToEntity(this EmailAccountModel model, EmailAccount destination)
 {
     return(model.MapTo(destination));
 }
 public static EmailAccount ToEntity(this EmailAccountModel model, EmailAccount destination)
 {
     return Mapper.Map(model, destination);
 }
        /// <summary>
        /// Sends a campaign to specified email
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="email">Email</param>
        public virtual void SendCampaign(Campaign campaign, EmailAccount emailAccount, string email)
        {
            if (campaign == null)
                throw new ArgumentNullException("campaign");

            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            var tokens = new List<Token>();
            _messageTokenProvider.AddWebTokens(tokens);
            var account = _accountService.GetAccountByEmail(email);
            if (account != null)
                _messageTokenProvider.AddAccountTokens(tokens, account);

            string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
            string body = _tokenizer.Replace(campaign.Body, tokens, true);

            var from = new MailAddress(emailAccount.Email, emailAccount.DisplayName);
            var to = new MailAddress(email);
            _emailSender.SendEmail(emailAccount, subject, body, from, to);
        }
Exemple #54
0
        public async Task <IActionResult> PostAsync([FromRoute] Guid organizationuuid, [FromBody] MapHiveUser user, string applicationContext = null, [FromQuery] EmailAccount ea = null)
        {
            //only owners or admins should be allowed to perform this action
            var callerId = Cartomatic.Utils.Identity.GetUserGuid();

            if (!(UserIsOrgOwner(callerId) || UserIsOrgAdmin(callerId)))
            {
                return(NotAllowed());
            }

            //this is an org user, so needs to be flagged as such!
            user.IsOrgUser            = true;
            user.ParentOrganizationId = organizationuuid;

            try
            {
                //initial email template customization
                var replacementData = new Dictionary <string, object>
                {
                    { "UserName", $"{user.GetFullUserName()} ({user.Email})" },
                    { "Email", user.Email },
                    { "RedirectUrl", this.GetRequestSource(HttpContext)?.Split('#')[0] }
                };

                var(emailAccount, emailTemplate) = await GetEmailStuffAsync("user_created", applicationContext);

                //use custom email account if provided
                if (ea != null && ea.SeemsComplete())
                {
                    emailAccount = ea;
                }

                //note:
                //org users and org roles are created against mh meta db!
                //This is where some env core objects are kept

                var createdUser = await MapHiveUser.CreateUserAccountAsync(GetDefaultDbContext(), user, EmailSender, emailAccount, emailTemplate?.Prepare(replacementData));

                if (createdUser != null)
                {
                    //user has been created, so now need to add it to the org with an appropriate role
                    await this.OrganizationContext.AddOrganizationUserAsync(GetDefaultDbContext(), createdUser.User);

                    //at this stage user should have had a member role assigned
                    //mkae sure to assign the one that has been asked for
                    if (user.OrganizationRole.HasValue && user.OrganizationRole != Organization.OrganizationRole.Member)
                    {
                        await this.OrganizationContext.ChangeOrganizationUserRoleAsync(GetDefaultDbContext(), user);
                    }

                    return(Ok(createdUser.User));
                }

                return(NotFound());
            }
            catch (Exception ex)
            {
                return(this.HandleException(ex));
            }
        }
        private int SendNotification(MessageTemplate messageTemplate,
                                     EmailAccount emailAccount, int languageId, IEnumerable<Token> tokens,
                                     string toEmailAddress, string toName)
        {
            //retrieve localized message template data
            var bcc = messageTemplate.GetLocalized((mt) => mt.BccEmailAddresses, languageId);
            var subject = messageTemplate.GetLocalized((mt) => mt.Subject, languageId);
            var body = messageTemplate.GetLocalized((mt) => mt.Body, languageId);

            //Replace subject and body tokens
            var subjectReplaced = _tokenizer.Replace(subject, tokens, false);
            var bodyReplaced = _tokenizer.Replace(body, tokens, false);

            var email = new QueuedEmail() {
                Priority = QueuedEmailPriority.High,
                From = emailAccount.Email,
                FromName = emailAccount.DisplayName,
                To = toEmailAddress,
                ToName = toName,
                CC = string.Empty,
                Bcc = bcc,
                Subject = subjectReplaced,
                Body = bodyReplaced,
                CreatedOnUtc = DateTime.UtcNow,
                EmailAccountId = emailAccount.Id
            };

            _queuedEmailService.InsertQueuedEmail(email);
            return email.Id;
        }
Exemple #56
0
        private void SeedEmailTemplates(string adminEmail, string installDomain)
        {
            var emailAccountService       = DependencyResolver.Resolve <IEmailAccountService>();
            var emailTemplateService      = DependencyResolver.Resolve <IEmailTemplateService>();
            var installEmailTemplatesPath = ServerHelper.MapPath("~/App_Data/Install/EmailTemplates/");

            if (installDomain.StartsWith("//"))
            {
                installDomain = installDomain.Substring(2);
            }
            var emailAccount = new EmailAccount()
            {
                Email    = "support@" + installDomain,
                FromName = "EvenCart",
                Host     = "",
                Port     = 485,
                UseDefaultCredentials = true,
                UseSsl   = true,
                UserName = "******"
            };

            emailAccountService.Insert(emailAccount);

            var masterTemplate = new EmailTemplate()
            {
                AdministrationEmail = adminEmail,
                IsMaster            = true,
                Subject             = "Master Template",
                TemplateSystemName  = EmailTemplateNames.Master,
                TemplateName        = "Master",
                IsSystem            = true,
                EmailAccountId      = emailAccount.Id,
                Template            = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.Master)
            };

            emailTemplateService.Insert(masterTemplate);

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Your account has been created",
                TemplateSystemName    = EmailTemplateNames.UserRegisteredMessage,
                TemplateName          = "User Registered",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.UserRegisteredMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "A new user has registered",
                TemplateSystemName    = EmailTemplateNames.UserRegisteredMessageToAdmin,
                TemplateName          = "User Registered Administrator",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.UserRegisteredMessageToAdmin),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Your account has been activated",
                TemplateSystemName    = EmailTemplateNames.UserActivatedMessage,
                TemplateName          = "User Activated",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.UserActivatedMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Activate your account",
                TemplateSystemName    = EmailTemplateNames.UserActivationLinkMessage,
                TemplateName          = "User Activation Link",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.UserActivationLinkMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "We have received a password reset request",
                TemplateSystemName    = EmailTemplateNames.PasswordRecoveryLinkMessage,
                TemplateName          = "Password Recovery Link",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.PasswordRecoveryLinkMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Your password has been changed",
                TemplateSystemName    = EmailTemplateNames.PasswordChangedMessage,
                TemplateName          = "Password Changed",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.PasswordChangedMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Your account has been deactivated",
                TemplateSystemName    = EmailTemplateNames.UserDeactivatedMessage,
                TemplateName          = "User Account Deactivated",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.UserDeactivatedMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Your account has been deactivated",
                TemplateSystemName    = EmailTemplateNames.UserDeactivatedMessageToAdmin,
                TemplateName          = "User Account Deactivated Administrator",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.UserDeactivatedMessageToAdmin),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Your account has been deleted",
                TemplateSystemName    = EmailTemplateNames.UserAccountDeletedMessage,
                TemplateName          = "User Account Deleted",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.UserAccountDeletedMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "A user account has been deleted",
                TemplateSystemName    = EmailTemplateNames.UserAccountDeletedMessageToAdmin,
                TemplateName          = "User Account Deleted Administrator",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.UserAccountDeletedMessageToAdmin),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Thank for your interest",
                TemplateSystemName    = EmailTemplateNames.InvitationRequestedMessage,
                TemplateName          = "Invitation Requested",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.InvitationRequestedMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "{{email}} has requested for an invitation",
                TemplateSystemName    = EmailTemplateNames.InvitationRequestedMessageToAdmin,
                TemplateName          = "Invitation Requested Administrator",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.InvitationRequestedMessageToAdmin),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "We invite you to join {{store.name}}",
                TemplateSystemName    = EmailTemplateNames.InvitationMessage,
                TemplateName          = "Invitation",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.InvitationMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Your recent order # {{order.orderNumber}}",
                TemplateSystemName    = EmailTemplateNames.OrderPlacedMessage,
                TemplateName          = "Order Placed",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.OrderPlacedMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Order # {{order.orderNumber}} placed by {{user.name}}",
                TemplateSystemName    = EmailTemplateNames.OrderPlacedMessageToAdmin,
                TemplateName          = "Order Placed Administrator",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.OrderPlacedMessageToAdmin),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Your recent order # {{order.orderNumber}} has been paid",
                TemplateSystemName    = EmailTemplateNames.OrderPaidMessage,
                TemplateName          = "Order Paid",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.OrderPaidMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Order # {{order.orderNumber}} placed by {{user.name}} has been paid",
                TemplateSystemName    = EmailTemplateNames.OrderPaidMessageToAdmin,
                TemplateName          = "Order Paid Administrator",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.OrderPaidMessageToAdmin),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Your order has been shipped",
                TemplateSystemName    = EmailTemplateNames.ShipmentShippedMessage,
                TemplateName          = "Order Shipped",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.ShipmentShippedMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Your order has been delivered",
                TemplateSystemName    = EmailTemplateNames.ShipmentDeliveredMessage,
                TemplateName          = "Order Delivered",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.ShipmentDeliveredMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "An order has been delivered",
                TemplateSystemName    = EmailTemplateNames.ShipmentDeliveredMessageToAdmin,
                TemplateName          = "Order Delivered Administrator",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.ShipmentDeliveredMessageToAdmin),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "The delivery of your recent order failed",
                TemplateSystemName    = EmailTemplateNames.ShipmentDeliveryFailedMessage,
                TemplateName          = "Order Delivery Failed",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.ShipmentDeliveryFailedMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "A recent order failed to deliver",
                TemplateSystemName    = EmailTemplateNames.ShipmentDeliveryFailedMessageToAdmin,
                TemplateName          = "Order Delivery Failed Administrator",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.ShipmentDeliveryFailedMessageToAdmin),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Return request for order # {{order.orderNumber}}",
                TemplateSystemName    = EmailTemplateNames.ReturnRequestCreatedMessage,
                TemplateName          = "Return Request Created",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.ReturnRequestCreatedMessage),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Return request for order # {{order.orderNumber}}",
                TemplateSystemName    = EmailTemplateNames.ReturnRequestCreatedMessageToAdmin,
                TemplateName          = "Return Request Created Administrator",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.ReturnRequestCreatedMessageToAdmin),
                ParentEmailTemplateId = masterTemplate.Id
            });

            emailTemplateService.Insert(new EmailTemplate()
            {
                AdministrationEmail   = adminEmail,
                IsMaster              = false,
                Subject               = "Contact Form Query - {{contact.subject}}",
                TemplateSystemName    = EmailTemplateNames.ContactUsMessageToAdmin,
                TemplateName          = "Contact Form Query Administrator",
                IsSystem              = true,
                EmailAccountId        = emailAccount.Id,
                Template              = ReadEmailTemplate(installEmailTemplatesPath, EmailTemplateNames.ContactUsMessageToAdmin),
                ParentEmailTemplateId = masterTemplate.Id
            });
        }
        protected int SendNotification(
			MessageTemplate messageTemplate,
            EmailAccount emailAccount, 
			int languageId, 
			IList<Token> tokens,
            string toEmailAddress, 
			string toName,
			string replyTo = null,
			string replyToName = null)
        {
            // retrieve localized message template data
            var bcc = messageTemplate.GetLocalized((mt) => mt.BccEmailAddresses, languageId);
            var subject = messageTemplate.GetLocalized((mt) => mt.Subject, languageId);
            var body = messageTemplate.GetLocalized((mt) => mt.Body, languageId);

            // Replace subject and body tokens
            var subjectReplaced = _tokenizer.Replace(subject, tokens, false);
            var bodyReplaced = _tokenizer.Replace(body, tokens, true);

            bodyReplaced = WebHelper.MakeAllUrlsAbsolute(bodyReplaced, _httpRequest);

            var email = new QueuedEmail
            {
                Priority = 5,
                From = emailAccount.Email,
                FromName = emailAccount.DisplayName,
                To = toEmailAddress,
                ToName = toName,
                CC = string.Empty,
                Bcc = bcc,
                ReplyTo = replyTo,
                ReplyToName = replyToName,
                Subject = subjectReplaced,
                Body = bodyReplaced,
                CreatedOnUtc = DateTime.UtcNow,
                EmailAccountId = emailAccount.Id,
                SendManually = messageTemplate.SendManually
            };

            // create attachments if any
            var fileIds = (new int?[]
                {
                    messageTemplate.GetLocalized(x => x.Attachment1FileId, languageId),
                    messageTemplate.GetLocalized(x => x.Attachment2FileId, languageId),
                    messageTemplate.GetLocalized(x => x.Attachment3FileId, languageId)
                })
                .Where(x => x.HasValue)
                .Select(x => x.Value)
                .ToArray();

            if (fileIds.Any())
            {
                var files = _downloadServioce.GetDownloadsByIds(fileIds);
                foreach (var file in files)
                {
                    email.Attachments.Add(new QueuedEmailAttachment
                    {
                        StorageLocation = EmailAttachmentStorageLocation.FileReference,
                        FileId = file.Id,
                        Name = (file.Filename.NullEmpty() ?? file.Id.ToString()) + file.Extension.EmptyNull(),
                        MimeType = file.ContentType.NullEmpty() ?? "application/octet-stream"
                    });
                }
            }

            // publish event so that integrators can add attachments, alter the email etc.
            _eventPublisher.Publish(new QueuingEmailEvent
            {
                EmailAccount = emailAccount,
                LanguageId = languageId,
                MessageTemplate = messageTemplate,
                QueuedEmail = email,
                Tokens = tokens
            });

            _queuedEmailService.InsertQueuedEmail(email);

            return email.Id;
        }
Exemple #58
0
        //http://aboutcode.net/postal/outside-aspnet.html
        //http://aboutcode.net/postal/multi-part.html
        //http://aboutcode.net/postal/
        public void SendPostalEmail(EmailAccount emailAccount, BasePostalMail mail, 
            IEnumerable<MailAttachment> attachments = null)
        {
            // Get the path to the directory containing views
            var viewsPath = CommonHelper.PostalViewPath;
           viewsPath = Path.GetFullPath(viewsPath);
            dynamic _mail = mail;
           
            var engines = new ViewEngineCollection();
            engines.Add(new FileSystemRazorViewEngine(viewsPath));
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host = emailAccount.Host;
                smtpClient.Port = emailAccount.Port;
                smtpClient.EnableSsl = emailAccount.EnableSsl;
                if (emailAccount.UseDefaultCredentials)
                    smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                else
                    smtpClient.Credentials = new NetworkCredential(emailAccount.Username, emailAccount.Password);

                var service = new EmailService(engines, () => smtpClient);
                if (attachments != null)
                {
                    if (attachments.Count() > 0)
                    {
                        foreach (MailAttachment s in attachments)
                        {
                            mail.Attach(new Attachment(s.FileStream, s.Name, s.ContentType.MediaType));
                        }
                    }
                }
              


                service.Send(mail);


            }
          
          
          
        }
        /// <summary>
        /// Sends a campaign to specified email
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="email">Email</param>
        public virtual void SendCampaign(Campaign campaign, EmailAccount emailAccount, string email)
        {
            if (campaign == null)
                throw new ArgumentNullException("campaign");

            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            var tokens = new List<Token>();
			_messageTokenProvider.AddStoreTokens(tokens, _storeContext.CurrentStore);
            _messageTokenProvider.AddNewsLetterSubscriptionTokens(tokens, new NewsLetterSubscription() {
                Email = email
            });

            var customer = _customerService.GetCustomerByEmail(email);
            if (customer != null)
                _messageTokenProvider.AddCustomerTokens(tokens, customer);
            
            string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
            string body = _tokenizer.Replace(campaign.Body, tokens, true);

			var to = new EmailAddress(email);
            var from = new EmailAddress(emailAccount.Email, emailAccount.DisplayName);

			var msg = new EmailMessage(to, subject, body, from);

            _emailSender.SendEmail(new SmtpContext(emailAccount), msg);
        }
Exemple #60
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="fromAddress">From address</param>
        /// <param name="fromName">From display name</param>
        /// <param name="toAddress">To address</param>
        /// <param name="toName">To display name</param>
        /// <param name="replyTo">ReplyTo address</param>
        /// <param name="replyToName">ReplyTo display name</param>
        /// <param name="bcc">BCC addresses list</param>
        /// <param name="cc">CC addresses list</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>
        public void SendEmail(EmailAccount emailAccount, string subject, string body,
            string fromAddress, string fromName, string toAddress, string toName,
             string replyTo = null, string replyToName = null,
            IEnumerable<string> bcc = null, IEnumerable<string> cc = null,

           IEnumerable<MailAttachment> attachments = null
           )
        {
            var message = new MailMessage();
            //from, to, reply to
            message.From = new MailAddress(fromAddress, fromName);
            message.To.Add(new MailAddress(toAddress, toName));
            if (!String.IsNullOrEmpty(replyTo))
            {
                message.ReplyToList.Add(new MailAddress(replyTo, replyToName));
            }

            //BCC
            if (bcc != null)
            {
                foreach (var address in bcc.Where(bccValue => !String.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(address.Trim());
                }
            }

            //CC
            if (cc != null)
            {
                foreach (var address in cc.Where(ccValue => !String.IsNullOrWhiteSpace(ccValue)))
                {
                    message.CC.Add(address.Trim());
                }
            }

            //content
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = true;
            if (attachments != null)
            {
                if (attachments.Count() > 0)
                {
                    foreach (MailAttachment mailAttachment in attachments)
                    {
                        var attachment = new Attachment(mailAttachment.FileStream, mailAttachment.Name,
                            mailAttachment.ContentType.MediaType);

                        message.Attachments.Add(attachment);
                    }
                  
                }
            }
            //create  the file attachment for this e-mail message
            //if (!String.IsNullOrEmpty(attachmentFilePath) &&
            //    File.Exists(attachmentFilePath))
            //{
            //    var attachment = new Attachment(attachmentFilePath);
            //    attachment.ContentDisposition.CreationDate = File.GetCreationTime(attachmentFilePath);
            //    attachment.ContentDisposition.ModificationDate = File.GetLastWriteTime(attachmentFilePath);
            //    attachment.ContentDisposition.ReadDate = File.GetLastAccessTime(attachmentFilePath);
            //    if (!String.IsNullOrEmpty(attachmentFileName))
            //    {
            //        attachment.Name = attachmentFileName;
            //    }
            //    message.Attachments.Add(attachment);
            //}

            //send email
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host = emailAccount.Host;
                smtpClient.Port = emailAccount.Port;
                smtpClient.EnableSsl = emailAccount.EnableSsl;
                if (emailAccount.UseDefaultCredentials)
                    smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                else
                    smtpClient.Credentials = new NetworkCredential(emailAccount.Username, emailAccount.Password);
                smtpClient.Send(message);
            }
        }