Exemplo n.º 1
0
            public void ThrowsArgumentExceptionWhenSenderNull()
            {
                var recipients = new EmailRecipients(
                    to: new[] { new MailAddress("*****@*****.**") });
                var emailBuilder = new Mock <IEmailBuilder>();

                emailBuilder
                .Setup(m => m.GetRecipients())
                .Returns(recipients)
                .Verifiable();
                emailBuilder
                .Setup(m => m.Sender)
                .Returns <MailAddress>(null)
                .Verifiable();

                var emailMessageEnqueuerMock = new Mock <IEmailMessageEnqueuer>();
                var messageService           = new AsynchronousEmailMessageService(
                    emailMessageEnqueuerMock.Object,
                    Mock.Of <ILogger <AsynchronousEmailMessageService> >(),
                    Mock.Of <IMessageServiceConfiguration>());

                Assert.ThrowsAsync <ArgumentException>(() => messageService.SendMessageAsync(emailBuilder.Object, false, false));

                emailBuilder.Verify();
                emailMessageEnqueuerMock.Verify(
                    m => m.SendEmailMessageAsync(It.IsAny <EmailMessageData>()),
                    Times.Never);
            }
Exemplo n.º 2
0
        public void SendEmail()
        {
            EmailClient client = CreateEmailClient();

            #region Snippet:Azure_Communication_Email_Send
            // Create the email content
            var emailContent = new EmailContent("This is the subject");
            emailContent.PlainText = "This is the body";

            // Create the recipient list
            var emailRecipients = new EmailRecipients(
                new List <EmailAddress>
            {
                new EmailAddress(
                    //@@ email: "<recipient email address>"
                    //@@ displayName: "<recipient displayname>"
                    /*@@*/ email: TestEnvironment.ToEmailAddress,
                    /*@@*/ displayName: "Customer Name")
            });

            // Create the EmailMessage
            var emailMessage = new EmailMessage(
                //@@ sender: "<Send email address>" // The email address of the domain registered with the Communication Services resource
                /*@@*/ sender: TestEnvironment.AzureManagedFromEmailAddress,
                emailContent,
                emailRecipients);

            SendEmailResult sendResult = client.Send(emailMessage);

            Console.WriteLine($"Email id: {sendResult.MessageId}");
            #endregion Snippet:Azure_Communication_Email_Send

            Assert.False(string.IsNullOrEmpty(sendResult.MessageId));
        }
Exemplo n.º 3
0
        public override IEmailRecipients GetRecipients()
        {
            var to = EmailRecipients.GetAllOwners(
                Package.PackageRegistration,
                requireEmailAllowed: false);

            return(new EmailRecipients(to));
        }
Exemplo n.º 4
0
 public static void SetQueueRecipient(EmailRecipients value)
 {
     if (_instance == null)
     {
         throw new Exception("Create instance first before accessing method.");
     }
     _instance._queueRecipient = value;
     Save();
 }
        public override IEmailRecipients GetRecipients()
        {
            var to = EmailRecipients.GetAllOwners(
                Package.PackageRegistration,
                requireEmailAllowed: true);

            return(new EmailRecipients(
                       to,
                       replyTo: new[] { FromAddress }));
        }
        public WatcherConfig GetWatcherConfig()
        {
            EmailRecipients email = EmailRecipients.Everyone;

            if (EmailRecipient.SelectedItem != null)
            {
                email = (EmailRecipients)EmailRecipient.SelectedItem;
            }
            return(new WatcherConfig(Identifier, (WatcherType)WatcherType.SelectedItem, false, ContentCompare.IsChecked ?? false, (NotifyFilters)FilterType.SelectedItem, FileFilter.Text, (WatcherChangeTypes)ChangeType.SelectedItem, (EmailType)EmailType.SelectedItem, Subfolder.IsChecked ?? false, _robot, email));
        }
Exemplo n.º 7
0
        public List <string> RecipientList()
        {
            List <string> recipientList = new List <string>();

            if (!string.IsNullOrEmpty(EmailRecipients))
            {
                recipientList = EmailRecipients.Split(new char[] { ';' }).ToList();
            }

            return(recipientList);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="emailRecipients"></param>
        /// <param name="conversationId"></param>
        /// <param name="properties"></param>
        /// <param name="exactTargetDelivery"></param>
        /// <param name="externalKeyOfTriggeredSendDefn"></param>
        /// <returns></returns>
        private async static Task ForwardRequestToIrisApi(EmailRecipients emailRecipients, Guid conversationId, Dictionary <string, string> properties, ExactTargetDelivery exactTargetDelivery, string externalKeyOfTriggeredSendDefn)
        {
            var appTicket = s2sAuthClient.GetAccessTokenAsync(MucpTargetSite, CancellationToken.None).Result;

            await publisher
            .CreateRequest()
            .WithEventName(externalKeyOfTriggeredSendDefn)
            .WithModelProperties(properties)
            .WithInstanceId(conversationId)
            .WithDelivery(exactTargetDelivery)
            .WithRecipient(emailRecipients)
            .WithAppTicket(appTicket)
            .SendAsync(TimeSpan.FromSeconds(120)).ConfigureAwait(false);
        }
Exemplo n.º 9
0
 public WatcherConfig(string id, WatcherType watcher, bool enabled, bool content, NotifyFilters filters, string file, WatcherChangeTypes change, EmailType email, bool subfolder, int robot = -1, EmailRecipients recipients = EmailRecipients.Everyone)
 {
     Id              = id;
     Enabled         = enabled;
     ContentCompare  = content;
     NotifyFilters   = filters;
     FileFilters     = file;
     ChangeType      = change;
     EmailType       = email;
     WatcherType     = watcher;
     Robot           = robot;
     EmailRecipients = recipients;
     Subfolder       = subfolder;
 }
Exemplo n.º 10
0
        public async Task SendEmailWithAttachmentAsync()
        {
            EmailClient client = CreateEmailClient();

            var emailContent = new EmailContent("This is the subject");

            emailContent.PlainText = "This is the body";

            var emailRecipients = new EmailRecipients(
                new List <EmailAddress>
            {
                new EmailAddress(
                    //@@ email: "<recipient email address>"
                    //@@ displayName: "<recipient displayname>"
                    /*@@*/ email: TestEnvironment.ToEmailAddress,
                    /*@@*/ displayName: "Customer Name")
            });

            #region Snippet:Azure_Communication_Email_Send_With_AttachmentsAsync
            // Create the EmailMessage
            var emailMessage = new EmailMessage(
                //@@ sender: "<Send email address>" // The email address of the domain registered with the Communication Services resource
                /*@@*/ sender: TestEnvironment.AzureManagedFromEmailAddress,
                emailContent,
                emailRecipients);

#if SNIPPET
            var filePath       = "<path to your file>";
            var attachmentName = "<name of your attachment>"
                                 EmailAttachmentType attachmentType = EmailAttachmentType.Txt;
#endif

            // Convert the file content into a Base64 string
#if SNIPPET
            byte[] bytes = File.ReadAllBytes(filePath);
            string attachmentFileInBytes = Convert.ToBase64String(bytes);
#else
            string attachmentName = "Attachment.txt";
            EmailAttachmentType attachmentType = EmailAttachmentType.Txt;
            var attachmentFileInBytes          = "VGhpcyBpcyBhIHRlc3Q=";
#endif
            var emailAttachment = new EmailAttachment(attachmentName, attachmentType, attachmentFileInBytes);

            emailMessage.Attachments.Add(emailAttachment);

            SendEmailResult sendResult = await client.SendAsync(emailMessage);

            #endregion Snippet:Azure_Communication_Email_Send_With_AttachmentsAsync
        }
            public void ThrowsArgumentExceptionWhenPlainTextAndHtmlBodyEmpty()
            {
                var recipients = new EmailRecipients(
                    to: new[] { new MailAddress("*****@*****.**") });
                var emailBuilder = new Mock <IEmailBuilder>();

                emailBuilder
                .Setup(m => m.Sender)
                .Returns(new MailAddress("*****@*****.**"))
                .Verifiable();
                emailBuilder
                .Setup(m => m.GetRecipients())
                .Returns(recipients)
                .Verifiable();
                emailBuilder
                .Setup(m => m.GetSubject())
                .Returns("subject")
                .Verifiable();
                emailBuilder
                .Setup(m => m.GetBody(EmailFormat.Html))
                .Returns <string>(null)
                .Verifiable();
                emailBuilder
                .Setup(m => m.GetBody(EmailFormat.PlainText))
                .Returns <string>(null)
                .Verifiable();

                var emailMessageEnqueuerMock = new Mock <IEmailMessageEnqueuer>();
                var messageService           = new AsynchronousEmailMessageService(
                    Configuration,
                    emailMessageEnqueuerMock.Object);

                Assert.ThrowsAsync <ArgumentException>(() => messageService.SendMessageAsync(emailBuilder.Object, false, false));

                emailBuilder.Verify();
                emailMessageEnqueuerMock.Verify(
                    m => m.SendEmailMessageAsync(It.IsAny <EmailMessageData>()),
                    Times.Never);
            }
        /// <summary>
        /// Email the Log file on file rolled
        /// </summary>
        /// <param name="filePath"></param>
        protected override void OnFileRolled(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return;
            }

            try
            {
                int totalErrors   = File.ReadAllLines(filePath).Count(line => Regex.IsMatch(line, ERROR_REGEX));
                int totalWarnings = File.ReadAllLines(filePath).Count(line => Regex.IsMatch(line, WARNING_REGEX));

                string environment = ApplicationSettingsHelper.LoadAppSetting("environment", false, string.Empty);
                if (!string.IsNullOrEmpty(environment))
                {
                    environment = "[{0}]".fmt(environment);
                }

                var info = new SysInfo();
                using (Emailer mailer = Kernel.Get <Emailer>())
                {
                    mailer.AddRecipient(EmailRecipients.Split(';', ','));
                    mailer.AttachFile(filePath);
                    mailer.Send(
                        "[{0} - {1}] {2} {3}"
                        .fmt(EmailSubject,
                             totalErrors != 0 ? "Error" : (totalWarnings != 0 ? "Warning" : "Information"),
                             environment,
                             DateTime.Now.ToString("dd/MM/yyyy")),
                        "{0}\r\n\r\nLog file attached".fmt(info.GetRamDiskUsage()));
                }
            }
            catch (Exception e)
            {
                Logger.WriteUnexpectedException(e, "Failed to email rolled file.", Category.GeneralError);
            }
        }
Exemplo n.º 13
0
        public FileWatchConfig(MainWindow main, string id, EmailType type, NotifyFilters filters,
                               WatcherChangeTypes change, WatcherType watcher, string file, bool content,
                               EmailRecipients watcherEmailRecipients, bool recurse)
        {
            _main = main;
            InitializeComponent();
            WatcherType.ItemsSource    = Enum.GetValues(typeof(WatcherType)).Cast <WatcherType>();
            ChangeType.ItemsSource     = Enum.GetValues(typeof(WatcherChangeTypes)).Cast <WatcherChangeTypes>();
            FilterType.ItemsSource     = Enum.GetValues(typeof(NotifyFilters)).Cast <NotifyFilters>();
            EmailType.ItemsSource      = Enum.GetValues(typeof(EmailType)).Cast <EmailType>();
            EmailRecipient.ItemsSource = Enum.GetValues(typeof(EmailRecipients)).Cast <EmailRecipients>();

            Identifier = id;
            ContentCompare.IsChecked    = content;
            EmailType.SelectedItem      = type;
            FilterType.SelectedItem     = filters;
            ChangeType.SelectedItem     = change;
            WatcherType.SelectedItem    = watcher;
            EmailRecipient.SelectedItem = watcherEmailRecipients;
            FileFilter.Text             = file;
            IdentLabel.Content          = id;
            Subfolder.IsChecked         = recurse;
            CheckExists();
        }
Exemplo n.º 14
0
 public static async Task <bool> SendMessage(EmailType type, QueueEntry entry, EmailRecipients recipients, TextBox log = null)
 {
     try
     {
         return(await SendMessage(entry.EmailAddress ?? Settings.EmailAddress, Settings.EmailServerAddress,
                                  $"[{type}] {DateTime.Now} - DVD Order Queue - {new FileInfo(entry.Source).Name}",
                                  $"See DVD Progress Page for current status.\r\nThis message may be delayed due to processing time, subject lists current time sent.\r\nSource:\t{entry.Source}\r\nStatus:\t{entry.Status}\r\nCurrent Time Elapsed:\t{entry.TimeSpan}\r\nRobot:\t{entry.Robot}\r\nLines:\r\n{entry.Line1}\r\n{entry.Line2}\r\n{entry.Line3}", recipients));
     }
     catch (Exception e)
     {
         if (log != null)
         {
             log.Text = e.Message;
         }
         return(false);
     }
 }
Exemplo n.º 15
0
        public static async Task <bool> SendMessage(string to, string from, string subject, string message, EmailRecipients recipients, TextBox log = null)
        {
            try
            {
                if (recipients == EmailRecipients.None)
                {
                    return(true);
                }

                using (var client = new SmtpClient(Settings.EmailServerSite, Settings.EmailServerPort))
                {
                    client.EnableSsl   = Settings.EmailServerSsl;
                    client.Credentials = new NetworkCredential(Settings.EmailServerUsername, Settings.EmailServerPassword);

                    using var mailMessage = new MailMessage(from, Settings.EmailAddress)
                          {
                              IsBodyHtml = true, Subject = subject, Body = message
                          };

                    if (recipients == EmailRecipients.Everyone || recipients == EmailRecipients.Sender)
                    {
                        foreach (var email in to.Split(';'))
                        {
                            mailMessage.To.Add(email);
                        }
                    }

                    await client.SendMailAsync(mailMessage);
                }
                return(true);
            }
            catch (Exception e)
            {
                if (log != null)
                {
                    log.Text = e.Message;
                }
                return(false);
            }
        }
        public override IEmailRecipients GetRecipients()
        {
            var to = EmailRecipients.GetOwnersSubscribedToPackagePushedNotification(_package.PackageRegistration);

            return(new EmailRecipients(to));
        }
        /// <summary>
        /// Handles incoming messages of AccountDeleteMessage type
        /// </summary>
        /// <param name="command"></param>
        /// <returns>True if processed successfully, false if we failed for some reason.</returns>
        /// <remarks>If accountManager.DeleteAccount throws, the entire method will throw and the message will go back into the queue.</remarks>
        public async Task <bool> HandleAsync(AccountDeleteMessage command)
        {
            var messageProcessed = true;
            var source           = command.Source;

            try
            {
                _logger.LogInformation("Processing Request from Source {Source}", source);
                _accountDeleteConfigurationAccessor.Value.VerifySource(source);

                var username = command.Username;
                var user     = _userService.FindByUsername(username);
                if (user == null)
                {
                    throw new UserNotFoundException();
                }

                if (_accountDeleteConfigurationAccessor.Value.RespectEmailContactSetting && !user.EmailAllowed)
                {
                    throw new EmailContactNotAllowedException();
                }

                var recipientEmail = user.EmailAddress;
                var deleteSuccess  = await _accountManager.DeleteAccount(user);

                _telemetryService.TrackDeleteResult(source, deleteSuccess);

                var baseEmailBuilder = _emailBuilderFactory.GetEmailBuilder(source, deleteSuccess);
                if (baseEmailBuilder != null)
                {
                    var toEmail = new List <MailAddress>();

                    var configuration = _accountDeleteConfigurationAccessor.Value;
                    var senderAddress = configuration.EmailConfiguration.GalleryOwner;
                    var ccEmail       = new List <MailAddress>();
                    // toEmail.Add(new MailAddress(recipientEmail)); // Temporarily disable sending to end user while we are in phase 1.
                    toEmail.Add(new MailAddress(senderAddress)); // Remove this when we switch to phase 2.
                    ccEmail.Add(new MailAddress(senderAddress));

                    var recipients   = new EmailRecipients(toEmail, ccEmail);
                    var emailBuilder = new DisposableEmailBuilder(baseEmailBuilder, recipients, username);
                    await _messenger.SendMessageAsync(emailBuilder);

                    _telemetryService.TrackEmailSent(source, user.EmailAllowed);
                    messageProcessed = true;
                }
            }
            catch (UnknownSourceException)
            {
                // Should definitely log if source isn't expected. Should we even send mail? or log and alert?
                // Log unknown source and fail.
                _logger.LogError("Unknown message source detected: {Source}.", command.Source);
                _telemetryService.TrackUnknownSource(source);
                messageProcessed = false;
            }
            catch (EmailContactNotAllowedException)
            {
                // Should we not send? or should we ignore the setting.
                _logger.LogWarning("User did not allow Email Contact.");
                _telemetryService.TrackEmailBlocked(source);
            }
            catch (UserNotFoundException)
            {
                _logger.LogWarning("User was not found. They may have already been deleted.");
                _telemetryService.TrackUserNotFound(source);
                messageProcessed = true;
            }
            catch (Exception e)
            {
                _logger.LogError(0, e, "An unknown exception occured: {ExceptionMessage}");
                throw e;
            }

            return(messageProcessed);
        }
Exemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dataTable">Data of flatfile</param>
        /// <param name="externalKeyOfTriggeredSendDefnUnderThisAccountName">Specify External Key of your Triggered Send Definition</param>
        public void SendTriggeredRequestsToSalesforceThruIrisApi(DataTable dataTable, string externalKeyOfTriggeredSendDefnUnderThisAccountName)
        {
            try
            {
                var         customProperties = new Dictionary <string, string>();
                var         emailRecipients  = new EmailRecipients();
                List <Task> tasks            = new List <Task>();

                var totalCount      = dataTable.Rows.Count;
                var currentPosition = 0;
                Console.WriteLine("Total: " + totalCount);

                foreach (DataRow dataRow in dataTable.Rows)
                {
                    currentPosition += 1;
                    customProperties.Clear();
                    for (var columnIdx = 0; columnIdx < dataRow.Table.Columns.Count; columnIdx++)
                    {
                        if (dataRow.Table.Columns[columnIdx].ColumnName.Equals("SubscriberKey"))
                        {
                            continue;
                        }
                        else if (dataRow.Table.Columns[columnIdx].ColumnName.Equals("EmailAddress"))
                        {
                            emailRecipients = new EmailRecipients
                            {
                                To = new List <string> {
                                    Convert.ToString(dataRow[dataRow.Table.Columns[columnIdx]])
                                }
                            }
                        }
                        ;
                        else
                        {
                            customProperties.Add(dataRow.Table.Columns[columnIdx].ColumnName, Convert.ToString(dataRow[dataRow.Table.Columns[columnIdx]]));
                        }
                    }

                    // This 'ConversationId' fights Salesforce from sending duplicate emails to end users despite multiple retries by the Tenant or IRIS.
                    //  So please define a unique identifier per email delivery. Make sure you don’t send same email with different conversation ID otherwise duplicate emails
                    //  would be send to the user.
                    var conversationId = Guid.NewGuid();

                    // Forwards the requests to IRIS API asychronously
                    tasks.Add(ForwardRequestToIrisApi(emailRecipients, conversationId, customProperties, exactTargetDelivery, externalKeyOfTriggeredSendDefnUnderThisAccountName));

                    Console.Write("\r" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + " | To go: " + (totalCount - currentPosition) + "                                 ");

                    if (currentPosition % 1000 == 0)
                    {
                        try
                        {
                            Task.WaitAll(tasks.ToArray());
                            tasks = new List <Task>();
                        }
                        catch (Exception e)
                        {
                            var message = string.Format(CultureInfo.InvariantCulture, "Request failed with exception: [{0}]", e);
                            Console.WriteLine(message);
                        }
                    }
                }

                Task.WaitAll(tasks.ToArray());

                Console.WriteLine(Environment.NewLine + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + " | Completed");
            }
            catch (Exception e)
            {
                var message = string.Format(CultureInfo.InvariantCulture, "Request failed with exception: [{0}]", e);
                Console.WriteLine(message);
            }

            // Forcing logs to be written to 'TextWriterOutput.log'. See trace listener settings in app.config
            Trace.Flush();
        }
Exemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="externalKeyOfTriggeredSendDefnUnderThisAccountName">Specify External Key of your Triggered Send Definition</param>
        public void SendTriggeredRequestToSalesforceThruIrisApi(string externalKeyOfTriggeredSendDefnUnderThisAccountName)
        {
            try
            {
                var emailAddress = "*****@*****.**"; // target email address

                var propertiesExample0 = new Dictionary <string, string>
                {
                    { "FirstName", "SampleFirstName001" },
                    { "LastName", " SampleLastName001" },
                    { "CustomProp001", " Sample CustomProp001" },
                    { "CustomProp002", " Sample CustomProp002" }
                };

                var emailRecipients = new EmailRecipients
                {
                    To = new List <string> {
                        emailAddress
                    }
                };

                var         justForExampleNumberOfTriggeredSendRequests = 10;
                List <Task> tasks = new List <Task>();

                for (int idx = 0; idx < justForExampleNumberOfTriggeredSendRequests; idx += 1)
                {
                    // This 'ConversationId' fights Salesforce from sending duplicate emails to end users despite multiple retries by the Tenant or IRIS.
                    //  So please define a unique identifier per email delivery. Make sure you don’t send same email with different conversation ID otherwise duplicate emails
                    //  would be send to the user.
                    var conversationId = Guid.NewGuid();

                    // Forwards the requests to IRIS API asychronously
                    tasks.Add(ForwardRequestToIrisApi(emailRecipients, conversationId, propertiesExample0, exactTargetDelivery, externalKeyOfTriggeredSendDefnUnderThisAccountName));

                    Console.Write("\r" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + " | To go: " + (justForExampleNumberOfTriggeredSendRequests - idx) + "              ");

                    if (idx % 1000 == 0)
                    {
                        try
                        {
                            Task.WaitAll(tasks.ToArray());
                            tasks = new List <Task>();
                        }
                        catch (Exception e)
                        {
                            var message = string.Format(CultureInfo.InvariantCulture, "Request failed with exception: [{0}]", e);
                            Console.WriteLine(message);
                        }
                    }
                }

                Task.WaitAll(tasks.ToArray());

                Console.WriteLine(Environment.NewLine + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + " | Completed");
            }
            catch (Exception e)
            {
                var message = string.Format(CultureInfo.InvariantCulture, "Request failed with exception: [{0}]", e);
                Console.WriteLine(message);
            }

            // Forcing logs to be written to 'TextWriterOutput.log'. See trace listener settings in app.config
            Trace.Flush();
        }
Exemplo n.º 20
0
            public async Task CreatesAndSendsExpectedMessageOnce()
            {
                var subject        = "subject";
                var htmlBody       = "html body";
                var plainTextBody  = "plain-text body";
                var toAddress      = "*****@*****.**";
                var ccAddress      = "*****@*****.**";
                var bccAddress     = "*****@*****.**";
                var replyToAddress = "*****@*****.**";
                var senderAddress  = "*****@*****.**";

                var recipients = new EmailRecipients(
                    to: new[] { new MailAddress(toAddress) },
                    cc: new[] { new MailAddress(ccAddress) },
                    bcc: new[] { new MailAddress(bccAddress) },
                    replyTo: new[] { new MailAddress(replyToAddress) });
                var emailBuilder = new Mock <IEmailBuilder>();

                emailBuilder
                .Setup(m => m.GetRecipients())
                .Returns(recipients)
                .Verifiable();
                emailBuilder
                .Setup(m => m.GetSubject())
                .Returns(subject)
                .Verifiable();
                emailBuilder
                .Setup(m => m.GetBody(EmailFormat.Html))
                .Returns(htmlBody)
                .Verifiable();
                emailBuilder
                .Setup(m => m.GetBody(EmailFormat.PlainText))
                .Returns(plainTextBody)
                .Verifiable();
                emailBuilder
                .Setup(m => m.Sender)
                .Returns(new MailAddress(senderAddress))
                .Verifiable();

                var emailMessageEnqueuerMock = new Mock <IEmailMessageEnqueuer>();
                var messageService           = new AsynchronousEmailMessageService(
                    emailMessageEnqueuerMock.Object,
                    Mock.Of <ILogger <AsynchronousEmailMessageService> >(),
                    Mock.Of <IMessageServiceConfiguration>());

                await messageService.SendMessageAsync(emailBuilder.Object, false, false);

                emailBuilder.Verify();
                emailMessageEnqueuerMock.Verify(
                    m => m.SendEmailMessageAsync(It.Is <EmailMessageData>(
                                                     d =>
                                                     d.HtmlBody == htmlBody &&
                                                     d.PlainTextBody == plainTextBody &&
                                                     d.Subject == subject &&
                                                     d.Sender == senderAddress &&
                                                     d.To.Contains(toAddress) &&
                                                     d.CC.Contains(ccAddress) &&
                                                     d.Bcc.Contains(bccAddress) &&
                                                     d.ReplyTo.Contains(replyToAddress) &&
                                                     d.MessageTrackingId != Guid.Empty &&
                                                     d.DeliveryCount == 0)),
                    Times.Once);

                emailMessageEnqueuerMock.Verify(m => m.SendEmailMessageAsync(It.IsAny <EmailMessageData>()), Times.Once);
            }
Exemplo n.º 21
0
        public static void history()
        {
            EmailContext     db          = new EmailContext();
            List <HistoryID> histories   = db.HistoryIDs.ToList();
            List <Message>   messagelist = new List <Message>();
            ulong?           newesthistoryid;

            //email all history ids being processed

            while (true)
            {
                //System.Threading.Thread.Sleep(2000);

                while (checkhistoryiddb(db, out newesthistoryid))
                {
                    bool synced = fullsync(out messagelist, out newesthistoryid);
                    bool allrecordsmarkedasprocessed = true;

                    if (synced && messagelist.Count > 0)
                    {
                        foreach (Message message in messagelist)
                        {
                            string subjectline = message.Payload.Headers[0].Value;
                            int    index       = subjectline.IndexOf("AwolrID:");
                            string awolrid     = message.Payload.Headers[0].Value.Substring(index + 8);
                            string rebuild     = subjectline.Substring(0, index - 1);
                            //write to database
                            // Decode
                            string body           = " ";
                            var    encodedString2 = message.Payload.Parts[0].Body.Data;
                            if (encodedString2 != null)
                            {
                                var bytes2 = Decode(encodedString2);
                                body = System.Text.Encoding.UTF8.GetString(bytes2); // Hello Base64Url encoding!
                            }

                            string to = null;
                            try
                            {
                                EmailRecipients emailRecipients =
                                    db.EmailRecipients.Where(er => er.bidfakeemailaddress.Contains(awolrid) || er.pidfakeemailaddress.Contains(awolrid)).FirstOrDefault();

                                if (emailRecipients.bidfakeemailaddress == awolrid)
                                {
                                    subjectline = rebuild + " AwolrID:" + emailRecipients.pidfakeemailaddress;
                                    to          = emailRecipients.bidrealemailaddress;
                                }
                                else
                                {
                                    subjectline = rebuild + " AwolrID:" + emailRecipients.bidfakeemailaddress;
                                    to          = emailRecipients.pidrealemailaddress;
                                }

                                try
                                {
                                    Email email = new Email();
                                    email.emailbody         = body;
                                    email.EmailRecipientsId = emailRecipients.Id;
                                    email.fromaddress       = "*****@*****.**";
                                    email.toaddress         = to;
                                    email.IdItem            = emailRecipients.IdItem;
                                    email.subject           = subjectline;
                                    email.ItemDescription   = subjectline;
                                    db.Emails.Add(email);
                                    db.SaveChanges();
                                    Console.WriteLine("New Email Record Generated For Email " + email.Id);
                                }
                                catch (Exception e)
                                {
                                    logger.Debug("Could not create relay response email. Returning method" + e.ToString() + "--------------\n\n");
                                    return;
                                }
                                //ModifyMessageRequest mods = new ModifyMessageRequest();
                                //List<String> addedlabels = new List<String> { "Label_5558979356135685998" };
                                //List<String> removedlabels = new List<String> { };
                                //mods.AddLabelIds = addedlabels;
                                //mods.RemoveLabelIds = removedlabels;

                                //try
                                //{
                                //    service.Users.Messages.Modify(mods, userId, message.Id).Execute();
                                //}
                                //catch (Exception e)
                                //{
                                //    allrecordsmarkedasprocessed = false;

                                //    throw new Exception("message could not be marked as processed.messageid " + message.Id + e.ToString());
                                //}
                                try
                                {
                                    service.Users.Messages.Delete(userId, message.Id).Execute();
                                }
                                catch (Exception e)
                                {
                                    logger.Debug("Could not delete processed email" + e.ToString());
                                }
                            }
                            catch (Exception e)
                            {
                                logger.Debug("message could not be marked as processed. messageid: " + message.Id + ":" + e.ToString() + "--------------\n\n");
                            }
                        }
                    }
                }
            }
            //foreach (HistoryID historyid in histories)
            //{

            //    long id = historyid.History;
            //    try
            //    {

            //        ulong historyid_start_conversionresult;
            //        List<History> result = null;
            //        try
            //        {
            //            historyid_start_conversionresult = Convert.ToUInt64(id);
            //            result = ListHistory(service, "*****@*****.**", historyid_start_conversionresult, messagelist);

            //        }
            //        catch (OverflowException)
            //        {
            //            Console.WriteLine("{0} is outside the range of the UInt64 type.", historyid);
            //        }
            //        if (result != null)
            //        {

            //            //loggerWrapper.PickAndExecuteLogging("Was able to retrieve history" + id.ToString());
            //        }
            //    }
            //    catch (Exception e)
            //    {

            //    }
            //}
        }
Exemplo n.º 22
0
            public async Task WillSendCopyToSenderIfAsked()
            {
                var subject       = "subject";
                var htmlBody      = "html body";
                var plainTextBody = "plain-text body";
                var toAddress     = "*****@*****.**";
                var ccAddress     = "*****@*****.**";
                var bccAddress    = "*****@*****.**";
                var fromAddress   = "*****@*****.**";
                var senderAddress = "*****@*****.**";

                var recipients = new EmailRecipients(
                    to: new[] { new MailAddress(toAddress) },
                    cc: new[] { new MailAddress(ccAddress) },
                    bcc: new[] { new MailAddress(bccAddress) },
                    replyTo: new[] { new MailAddress(fromAddress) });
                var emailBuilder = new Mock <IEmailBuilder>();

                emailBuilder
                .Setup(m => m.GetRecipients())
                .Returns(recipients)
                .Verifiable();
                emailBuilder
                .Setup(m => m.GetSubject())
                .Returns(subject)
                .Verifiable();
                emailBuilder
                .Setup(m => m.GetBody(EmailFormat.Html))
                .Returns(htmlBody)
                .Verifiable();
                emailBuilder
                .Setup(m => m.GetBody(EmailFormat.PlainText))
                .Returns(plainTextBody)
                .Verifiable();
                emailBuilder
                .Setup(m => m.Sender)
                .Returns(new MailAddress(senderAddress))
                .Verifiable();

                var messageServiceConfiguration = new TestMessageServiceConfiguration();
                var emailMessageEnqueuerMock    = new Mock <IEmailMessageEnqueuer>();
                var messageService = new AsynchronousEmailMessageService(
                    emailMessageEnqueuerMock.Object,
                    Mock.Of <ILogger <AsynchronousEmailMessageService> >(),
                    messageServiceConfiguration);

                // We want to copy the sender but not disclose the sender address
                await messageService.SendMessageAsync(
                    emailBuilder.Object,
                    copySender : true,
                    discloseSenderAddress : false);

                emailBuilder.Verify();

                // Verify the original email is sent (not disclosing the sender address)
                emailMessageEnqueuerMock.Verify(
                    m => m.SendEmailMessageAsync(It.Is <EmailMessageData>(
                                                     d =>
                                                     d.HtmlBody == htmlBody &&
                                                     d.PlainTextBody == plainTextBody &&
                                                     d.Subject == subject &&
                                                     d.Sender == senderAddress &&
                                                     d.To.Contains(toAddress) &&
                                                     d.CC.Contains(ccAddress) &&
                                                     d.Bcc.Contains(bccAddress) &&
                                                     d.ReplyTo.Contains(fromAddress) &&
                                                     d.MessageTrackingId != Guid.Empty &&
                                                     d.DeliveryCount == 0)),
                    Times.Once);

                // Verify a copy is sent to the sender
                var expectedPlainTextBody = string.Format(
                    CultureInfo.CurrentCulture,
                    "You sent the following message via {0}: {1}{1}{2}",
                    messageServiceConfiguration.GalleryOwner.DisplayName,
                    Environment.NewLine,
                    plainTextBody);

                var expectedHtmlBody = string.Format(
                    CultureInfo.CurrentCulture,
                    "You sent the following message via {0}: {1}{1}{2}",
                    messageServiceConfiguration.GalleryOwner.DisplayName,
                    Environment.NewLine,
                    htmlBody);

                emailMessageEnqueuerMock.Verify(
                    m => m.SendEmailMessageAsync(It.Is <EmailMessageData>(
                                                     d =>
                                                     d.HtmlBody == expectedHtmlBody &&
                                                     d.PlainTextBody == expectedPlainTextBody &&
                                                     d.Subject == subject + " [Sender Copy]" &&
                                                     d.Sender == messageServiceConfiguration.GalleryOwner.Address &&
                                                     d.To.Single() == fromAddress &&
                                                     !d.CC.Any() &&
                                                     !d.Bcc.Any() &&
                                                     d.ReplyTo.Single() == fromAddress &&
                                                     d.MessageTrackingId != Guid.Empty &&
                                                     d.DeliveryCount == 0)),
                    Times.Once);

                emailMessageEnqueuerMock.Verify(m => m.SendEmailMessageAsync(It.IsAny <EmailMessageData>()), Times.Exactly(2));
            }
Exemplo n.º 23
0
        /// <summary>
        /// Handles incoming messages of AccountDeleteMessage type
        /// </summary>
        /// <param name="command"></param>
        /// <returns>True if processed successfully, false if we failed for some reason.</returns>
        /// <remarks>If accountManager.DeleteAccount throws, the entire method will throw and the message will go back into the queue.</remarks>
        public async Task <bool> HandleAsync(AccountDeleteMessage command)
        {
            var messageProcessed = true;
            var source           = command.Source;

            try
            {
                _logger.LogInformation("Processing Request from Source {Source}", source);
                _accountDeleteConfigurationAccessor.Value.GetSourceConfiguration(source);

                var username = command.Username;
                var user     = _userService.FindByUsername(username);
                if (user == null)
                {
                    throw new UserNotFoundException();
                }

                var recipientEmail = user.EmailAddress;
                var emailAllowed   = user.EmailAllowed;
                var deleteSuccess  = await _accountManager.DeleteAccount(user, source);

                _telemetryService.TrackDeleteResult(source, deleteSuccess);

                if (recipientEmail == null)
                {
                    _logger.LogWarning("User has no confirmed email address. The user has been deleted but no email was sent.");
                    _telemetryService.TrackUnconfirmedUser(source);
                    messageProcessed = true;
                }
                else if (_accountDeleteConfigurationAccessor.Value.RespectEmailContactSetting && !emailAllowed)
                {
                    _logger.LogWarning("User did not allow Email Contact. The user has been deleted but no email was sent.");
                    _telemetryService.TrackEmailBlocked(source);
                    messageProcessed = true;
                }
                else
                {
                    var baseEmailBuilder = _emailBuilderFactory.GetEmailBuilder(source, deleteSuccess);
                    if (baseEmailBuilder != null)
                    {
                        var toEmail = new List <MailAddress>();

                        var configuration = _accountDeleteConfigurationAccessor.Value;
                        var senderAddress = configuration.EmailConfiguration.GalleryOwner;
                        var ccEmail       = new List <MailAddress>();
                        toEmail.Add(new MailAddress(recipientEmail));
                        ccEmail.Add(new MailAddress(senderAddress));

                        var recipients   = new EmailRecipients(toEmail, ccEmail);
                        var emailBuilder = new DisposableEmailBuilder(baseEmailBuilder, recipients, username);
                        await _messenger.SendMessageAsync(emailBuilder);

                        _telemetryService.TrackEmailSent(source, emailAllowed);
                        messageProcessed = true;
                    }
                }
            }
            catch (UnknownSourceException)
            {
                // Should definitely log if source isn't expected. Should we even send mail? or log and alert?
                // Log unknown source and fail.
                _logger.LogError("Unknown message source detected: {Source}.", command.Source);
                _telemetryService.TrackUnknownSource(source);
                messageProcessed = false;
            }
            catch (UserNotFoundException)
            {
                _logger.LogWarning("User was not found. They may have already been deleted.");
                _telemetryService.TrackUserNotFound(source);
                messageProcessed = true;
            }
            catch (Exception e)
            {
                _logger.LogError(e, "An unknown exception occurred.");
                throw;
            }

            return(messageProcessed);
        }