/// <summary> /// Deleted a queued email /// </summary> /// <param name="queuedEmail">Queued email</param> public virtual void DeleteQueuedEmail(QueuedEmail queuedEmail) { if (queuedEmail == null) throw new ArgumentNullException("queuedEmail"); _queuedEmailRepository.Delete(queuedEmail); //event notification _eventPublisher.EntityDeleted(queuedEmail); }
public void Can_save_and_load_queuedEmail() { var qe = new QueuedEmail() { Priority = 1, From = "From", FromName = "FromName", To = "To", ToName = "ToName", CC = "CC", Bcc = "Bcc", Subject = "Subject", Body = "Body", CreatedOnUtc = new DateTime(2010, 01, 01), SentTries = 5, SentOnUtc = new DateTime(2010, 02, 02), EmailAccount = new EmailAccount { Email = "*****@*****.**", DisplayName = "Administrator", Host = "127.0.0.1", Port = 125, Username = "******", Password = "******", EnableSsl = true, UseDefaultCredentials = true } }; var fromDb = SaveAndLoadEntity(qe); fromDb.ShouldNotBeNull(); fromDb.Priority.ShouldEqual(1); fromDb.From.ShouldEqual("From"); fromDb.FromName.ShouldEqual("FromName"); fromDb.To.ShouldEqual("To"); fromDb.ToName.ShouldEqual("ToName"); fromDb.CC.ShouldEqual("CC"); fromDb.Bcc.ShouldEqual("Bcc"); fromDb.Subject.ShouldEqual("Subject"); fromDb.Body.ShouldEqual("Body"); fromDb.CreatedOnUtc.ShouldEqual(new DateTime(2010, 01, 01)); fromDb.SentTries.ShouldEqual(5); fromDb.SentOnUtc.Value.ShouldEqual(new DateTime(2010, 02, 02)); fromDb.EmailAccount.ShouldNotBeNull(); fromDb.EmailAccount.DisplayName.ShouldEqual("Administrator"); }
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); 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 }; _queuedEmailService.InsertQueuedEmail(email); return email.Id; }
/// <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; }
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; }
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 static QueuedEmail ToEntity(this QueuedEmailModel model, QueuedEmail destination) { return Mapper.Map(model, destination); }
public ActionResult SendEmail(CustomerModel model) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers)) return AccessDeniedView(); var customer = _customerService.GetCustomerById(model.Id); if (customer == null) //No customer found with the specified id return RedirectToAction("List"); try { if (String.IsNullOrWhiteSpace(customer.Email)) throw new SmartException("Customer email is empty"); if (!customer.Email.IsEmail()) throw new SmartException("Customer email is not valid"); if (String.IsNullOrWhiteSpace(model.SendEmail.Subject)) throw new SmartException("Email subject is empty"); if (String.IsNullOrWhiteSpace(model.SendEmail.Body)) throw new SmartException("Email body is empty"); var emailAccount = _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId); if (emailAccount == null) emailAccount = _emailAccountService.GetAllEmailAccounts().FirstOrDefault(); if (emailAccount == null) throw new SmartException("Email account can't be loaded"); var email = new QueuedEmail() { EmailAccountId = emailAccount.Id, FromName = emailAccount.DisplayName, From = emailAccount.Email, ToName = customer.GetFullName(), To = customer.Email, Subject = model.SendEmail.Subject, Body = model.SendEmail.Body, CreatedOnUtc = DateTime.UtcNow, }; _queuedEmailService.InsertQueuedEmail(email); NotifySuccess(_localizationService.GetResource("Admin.Customers.Customers.SendEmail.Queued")); } catch (Exception exc) { NotifyError(exc.Message); } return RedirectToAction("Edit", new { id = customer.Id }); }
public ActionResult Requeue(QueuedEmailModel queuedEmailModel) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageQueue)) return AccessDeniedView(); var queuedEmail = _queuedEmailService.GetQueuedEmailById(queuedEmailModel.Id); if (queuedEmail == null) return RedirectToAction("List"); var requeuedEmail = new QueuedEmail { Priority = queuedEmail.Priority, From = queuedEmail.From, FromName = queuedEmail.FromName, To = queuedEmail.To, ToName = queuedEmail.ToName, CC = queuedEmail.CC, Bcc = queuedEmail.Bcc, Subject = queuedEmail.Subject, Body = queuedEmail.Body, CreatedOnUtc = DateTime.UtcNow, EmailAccountId = queuedEmail.EmailAccountId, SendManually = queuedEmail.SendManually }; _queuedEmailService.InsertQueuedEmail(requeuedEmail); NotifySuccess(_localizationService.GetResource("Admin.System.QueuedEmails.Requeued")); return RedirectToAction("Edit", requeuedEmail.Id); }
/// <summary> /// Sends a queued email /// </summary> /// <param name="queuedEmail">Queued email</param> /// <returns>Whether the operation succeeded</returns> public virtual bool SendEmail(QueuedEmail queuedEmail) { var result = false; try { var bcc = String.IsNullOrWhiteSpace(queuedEmail.Bcc) ? null : queuedEmail.Bcc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var cc = String.IsNullOrWhiteSpace(queuedEmail.CC) ? null : queuedEmail.CC.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var smtpContext = new SmtpContext(queuedEmail.EmailAccount); var msg = new EmailMessage( new EmailAddress(queuedEmail.To, queuedEmail.ToName), queuedEmail.Subject, queuedEmail.Body, new EmailAddress(queuedEmail.From, queuedEmail.FromName)); if (queuedEmail.ReplyTo.HasValue()) { msg.ReplyTo.Add(new EmailAddress(queuedEmail.ReplyTo, queuedEmail.ReplyToName)); } if (cc != null) { msg.Cc.AddRange(cc.Where(x => x.HasValue()).Select(x => new EmailAddress(x))); } if (bcc != null) { msg.Bcc.AddRange(bcc.Where(x => x.HasValue()).Select(x => new EmailAddress(x))); } _emailSender.SendEmail(smtpContext, msg); queuedEmail.SentOnUtc = DateTime.UtcNow; result = true; } catch (Exception exc) { _logger.Error(string.Concat(_localizationService.GetResource("Admin.Common.ErrorSendingEmail"), ": ", exc.Message), exc); } finally { queuedEmail.SentTries = queuedEmail.SentTries + 1; UpdateQueuedEmail(queuedEmail); } return result; }
internal EmailMessage ConvertEmail(QueuedEmail qe) { // 'internal' for testing purposes var msg = new EmailMessage( new EmailAddress(qe.To, qe.ToName), qe.Subject, qe.Body, new EmailAddress(qe.From, qe.FromName)); if (qe.ReplyTo.HasValue()) { msg.ReplyTo.Add(new EmailAddress(qe.ReplyTo, qe.ReplyToName)); } AddEmailAddresses(qe.CC, msg.Cc); AddEmailAddresses(qe.Bcc, msg.Bcc); if (qe.Attachments != null && qe.Attachments.Count > 0) { foreach (var qea in qe.Attachments) { Attachment attachment = null; if (qea.StorageLocation == EmailAttachmentStorageLocation.Blob) { var data = qea.Data; if (data != null && data.Length > 0) { attachment = new Attachment(data.ToStream(), qea.Name, qea.MimeType); } } else if (qea.StorageLocation == EmailAttachmentStorageLocation.Path) { var path = qea.Path; if (path.HasValue()) { if (path[0] == '~' || path[0] == '/') { path = CommonHelper.MapPath(VirtualPathUtility.ToAppRelative(path), false); } if (File.Exists(path)) { attachment = new Attachment(path, qea.MimeType); attachment.Name = qea.Name; } } } else if (qea.StorageLocation == EmailAttachmentStorageLocation.FileReference) { var file = qea.File; if (file != null && file.UseDownloadUrl == false && file.DownloadBinary != null && file.DownloadBinary.Length > 0) { attachment = new Attachment(file.DownloadBinary.ToStream(), file.Filename + file.Extension, file.ContentType); } } if (attachment != null) { msg.Attachments.Add(attachment); } } } return msg; }
public virtual void UpdateQueuedEmail(QueuedEmail queuedEmail) { if (queuedEmail == null) throw new ArgumentNullException("queuedEmail"); _queuedEmailRepository.Update(queuedEmail); //event notification _services.EventPublisher.EntityUpdated(queuedEmail); }
public virtual bool SendEmail(QueuedEmail queuedEmail) { var result = false; try { var smtpContext = new SmtpContext(queuedEmail.EmailAccount); var msg = ConvertEmail(queuedEmail); _emailSender.SendEmail(smtpContext, msg); queuedEmail.SentOnUtc = DateTime.UtcNow; result = true; } catch (Exception exc) { Logger.Error(string.Concat(T("Admin.Common.ErrorSendingEmail"), ": ", exc.Message), exc); } finally { queuedEmail.SentTries = queuedEmail.SentTries + 1; UpdateQueuedEmail(queuedEmail); } return result; }
public void Can_convert_email() { var qe = new QueuedEmail { Bcc = "[email protected];[email protected]", Body = "Body", CC = "[email protected];[email protected]", CreatedOnUtc = DateTime.UtcNow, From = "*****@*****.**", FromName = "FromName", Priority = 10, ReplyTo = "*****@*****.**", ReplyToName = "ReplyToName", Subject = "Subject", To = "*****@*****.**", ToName = "ToName" }; // load attachment file resource and save as file var asm = typeof(QueuedEmailServiceTests).Assembly; var pdfStream = asm.GetManifestResourceStream("{0}.Messages.Attachment.pdf".FormatInvariant(asm.GetName().Name)); var pdfBinary = pdfStream.ToByteArray(); pdfStream.Seek(0, SeekOrigin.Begin); var path1 = "~/Attachment.pdf"; var path2 = CommonHelper.MapPath(path1, false); Assert.IsTrue(pdfStream.ToFile(path2)); var attachBlob = new QueuedEmailAttachment { StorageLocation = EmailAttachmentStorageLocation.Blob, Data = pdfBinary, Name = "blob.pdf", MimeType = "application/pdf" }; var attachPath1 = new QueuedEmailAttachment { StorageLocation = EmailAttachmentStorageLocation.Path, Path = path1, Name = "path1.pdf", MimeType = "application/pdf" }; var attachPath2 = new QueuedEmailAttachment { StorageLocation = EmailAttachmentStorageLocation.Path, Path = path2, Name = "path2.pdf", MimeType = "application/pdf" }; var attachFile = new QueuedEmailAttachment { StorageLocation = EmailAttachmentStorageLocation.FileReference, Name = "file.pdf", MimeType = "application/pdf", File = new Download { ContentType = "application/pdf", DownloadBinary = pdfBinary, Extension = ".pdf", Filename = "file" } }; qe.Attachments.Add(attachBlob); qe.Attachments.Add(attachFile); qe.Attachments.Add(attachPath1); qe.Attachments.Add(attachPath2); var msg = _queuedEmailService.ConvertEmail(qe); Assert.IsNotNull(msg); Assert.IsNotNull(msg.To); Assert.IsNotNull(msg.From); Assert.AreEqual(msg.ReplyTo.Count, 1); Assert.AreEqual(qe.ReplyTo, msg.ReplyTo.First().Address); Assert.AreEqual(qe.ReplyToName, msg.ReplyTo.First().DisplayName); Assert.AreEqual(msg.Cc.Count, 2); Assert.AreEqual(msg.Cc.First().Address, "*****@*****.**"); Assert.AreEqual(msg.Cc.ElementAt(1).Address, "*****@*****.**"); Assert.AreEqual(msg.Bcc.Count, 2); Assert.AreEqual(msg.Bcc.First().Address, "*****@*****.**"); Assert.AreEqual(msg.Bcc.ElementAt(1).Address, "*****@*****.**"); Assert.AreEqual(qe.Subject, msg.Subject); Assert.AreEqual(qe.Body, msg.Body); Assert.AreEqual(msg.Attachments.Count, 4); var attach1 = msg.Attachments.First(); var attach2 = msg.Attachments.ElementAt(1); var attach3 = msg.Attachments.ElementAt(2); var attach4 = msg.Attachments.ElementAt(3); // test file names Assert.AreEqual(attach1.Name, "blob.pdf"); Assert.AreEqual(attach2.Name, "file.pdf"); Assert.AreEqual(attach3.Name, "path1.pdf"); Assert.AreEqual(attach4.Name, "path2.pdf"); // test file streams Assert.AreEqual(attach1.ContentStream.Length, pdfBinary.Length); Assert.AreEqual(attach2.ContentStream.Length, pdfBinary.Length); Assert.Greater(attach3.ContentStream.Length, 0); Assert.Greater(attach4.ContentStream.Length, 0); // cleanup msg.Attachments.Each(x => x.Dispose()); msg.Attachments.Clear(); // delete attachment file File.Delete(path2); }