Ejemplo n.º 1
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir  = RunExamples.GetDataDir_Exchange();
            string dstEmail = dataDir + "Message.msg";

            // Create instance of ExchangeClient class by giving credentials
            IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");

            MailMessageLoadOptions loadOptions = new MailMessageLoadOptions();

            loadOptions.MessageFormat         = MessageFormat.Msg;
            loadOptions.FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments;

            // load task from .msg file
            MailMessage eml = MailMessage.Load(dstEmail, loadOptions);

            eml.From = "*****@*****.**";
            eml.To.Clear();
            eml.To.Add(new Aspose.Email.Mail.MailAddress("*****@*****.**"));

            client.Send(eml);

            Console.WriteLine(Environment.NewLine + "Task sent on Exchange Server successfully.");
        }
        private void Initialise(Email email, MailboxProfile profile)
        {
            // Assign parameters to class members
            this.email   = email;
            this.profile = profile;

            // Load the Mail Message
            var options = new MailMessageLoadOptions();

            options.FileCompatibilityMode = FileCompatibilityMode.SkipValidityChecking;
            options.MessageFormat         = email.MessageFilePath.ToLower().EndsWith("msg") ? MessageFormat.Msg : MessageFormat.Eml;

            this.message = MailMessage.Load(email.MessageFilePath, options);
        }
Ejemplo n.º 3
0
        public static void Run()
        {
            // ExStart:ReadMessageByPreservingTNEFAttachments
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_Email();

            MailMessageLoadOptions options = new MailMessageLoadOptions();

            options.MessageFormat = MessageFormat.Eml;
            // This will Preserve the TNEF attachment as it is, file contains the TNEF attachment
            options.FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments;
            MailMessage eml = MailMessage.Load(dataDir + "Attachments.eml", options);

            foreach (Attachment attachment in eml.Attachments)
            {
                Console.WriteLine(attachment.Name);
            }
            // ExEnd:ReadMessageByPreservingTNEFAttachments
        }
Ejemplo n.º 4
0
        private void ExtractMessage(Stream stream, String safeFile, String format)
        {
            MailMessage message = null;

            try
            {
                var options = new MailMessageLoadOptions();
                options.FileCompatibilityMode = FileCompatibilityMode.SkipValidityChecking;

                switch (format)
                {
                case "eml":
                    options.MessageFormat = MessageFormat.Eml;
                    break;

                case "msg":
                    options.MessageFormat = MessageFormat.Msg;
                    break;
                }

                message = MailMessage.Load(stream, options);
            }
            catch
            {
                String file = GetAttachmentFileName(safeFile);

                using (var fs = File.Create(file))
                {
                    Byte[] buffer = new Byte[stream.Length];
                    stream.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, buffer.Length);
                }

                Documents.Add(new Document(file, safeFile, SaveToPath, batchNumber, emailID, DocumentSource.Attachment));

                return;
            }

            ExtractDocuments(message, true);
        }
        public static void Run()
        {
            // ExStart:SendTaskRequestUsingIEWSClient
            string dataDir = RunExamples.GetDataDir_Exchange();
            // Create instance of ExchangeClient class by giving credentials
            IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");

            MailMessageLoadOptions loadOptions = new MailMessageLoadOptions();

            loadOptions.MessageFormat         = MessageFormat.Msg;
            loadOptions.FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments;

            // load task from .msg file
            MailMessage eml = MailMessage.Load(dataDir + "task.msg", loadOptions);

            eml.From = "*****@*****.**";
            eml.To.Clear();
            eml.To.Add(new MailAddress("*****@*****.**"));

            client.Send(eml);
            // ExEnd:SendTaskRequestUsingIEWSClient
        }
Ejemplo n.º 6
0
        public static void Run()
        {
            // ExStart:SendMessageAsTNEF
            var emlFileName = RunExamples.GetDataDir_Email() + "Message.eml";      // A TNEF Email
            MailMessageLoadOptions options = new MailMessageLoadOptions();

            options.MessageFormat = MessageFormat.Eml;
            MailMessage eml = MailMessage.Load(emlFileName, options);

            eml.From = "*****@*****.**";
            eml.To.Clear();
            eml.To.Add(new MailAddress("*****@*****.**"));
            eml.Subject = "With PreserveTnef flag during loading";
            eml.Date    = DateTime.Now;

            SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "somename", "password");

            client.SecurityOptions = SecurityOptions.Auto;
            client.UseTnef         = true; // Use this flag to send as TNEF
            client.Send(eml);
            // ExEnd:SendMessageAsTNEF
        }
Ejemplo n.º 7
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Exchange();
            string dstEmail = dataDir + "Message.msg";
            
            // Create instance of ExchangeClient class by giving credentials
            IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");

            MailMessageLoadOptions loadOptions = new MailMessageLoadOptions();
            loadOptions.MessageFormat = MessageFormat.Msg;
            loadOptions.FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments;

            // load task from .msg file
            MailMessage eml = MailMessage.Load(dstEmail, loadOptions);
            eml.From = "*****@*****.**";
            eml.To.Clear();
            eml.To.Add(new Aspose.Email.Mail.MailAddress("*****@*****.**"));

            client.Send(eml);

            Console.WriteLine(Environment.NewLine + "Task sent on Exchange Server successfully.");
        }
Ejemplo n.º 8
0
        private void listViewAttachments_DoubleClick(object sender, EventArgs e)
        {
            var attachment = SelectedAttachment;

            if (attachment != null)
            {
                string tempFilePath = Path.Combine(Path.GetTempPath(), "EmailImport.Viewer");

                if (attachment.IsEmbeddedMessage())
                {
                    tempFilePath = Path.Combine(tempFilePath, attachment.GetSafeFileName() + ".eml");

                    var options = new MailMessageLoadOptions()
                    {
                        FileCompatibilityMode = FileCompatibilityMode.SkipValidityChecking,
                        MessageFormat         = MessageFormat.Eml
                    };

                    var message = attachment.GetEmbeddedMessage(options);

                    message.Save(tempFilePath, MessageFormat.Eml);
                }
                else
                {
                    tempFilePath = Path.Combine(tempFilePath, attachment.GetSafeFileName());
                    attachment.Save(tempFilePath);
                }

                using (Process process = Process.Start(tempFilePath))
                {
                    if (process != null)
                    {
                        process.WaitForExit();
                    }
                }
            }
        }
Ejemplo n.º 9
0
        private void ErrorBatchOutput()
        {
            try
            {
                // Get available emails
                var emails = GetConversionErrorEmails();

                // Process any emails
                if (emails.Any())
                {
                    // Loop through the emails in error
                    foreach (var email in emails)
                    {
                        if (!timer.Enabled)
                        {
                            break;
                        }
                        try
                        {
                            // Get the mailbox required for the conversion
                            var profile = Settings.MailboxProfiles[email.MailboxGUID.Value];
                            //produce error output in asynchronous thread
                            try
                            {
                                errorbatchprocess = new ErrorEmailConverter();
                                errorbatchprocess.BeginAsync(email, profile);
                            }
                            catch (Exception e)
                            {
                                // Add custom data for logging purposes
                                e.Data.Add("MailboxGUID", profile.MailboxGUID);

                                // Log the error
                                ConfigLogger.Instance.LogError(email.EmailID, e);

                                // Update the email status
                                UpdateStatus(EmailStatus.Error, email, GetErrorXml(e.ToString(), profile.ErrorHandling.Unknown.ToString(), true));
                            }
                            // If there are any errors with an action of Escalate then escalate these as opposed to rejecting
                            //var escalate = (email.Errors != null && email.Errors.Descendants("Error").Any(e => (String)e.Attribute("action") == "Escalate")) ||
                            //                   (String.IsNullOrWhiteSpace(profile.TemplateTo) && String.IsNullOrWhiteSpace(profile.TemplateCc) && String.IsNullOrWhiteSpace(profile.TemplateBcc));

                            MailMessage error = null;

                            try
                            {
                                try
                                {
                                    var options = new MailMessageLoadOptions();
                                    options.FileCompatibilityMode = FileCompatibilityMode.SkipValidityChecking;
                                    options.MessageFormat         = email.MessageFilePath.ToLower().EndsWith("msg") ? MessageFormat.Msg : MessageFormat.Eml;

                                    error = MailMessage.Load(email.MessageFilePath, options);
                                }
                                catch
                                { }
                            }
                            finally
                            {
                                if (error != null)
                                {
                                    error.Dispose();
                                }
                            }

                            // Update the status to Forward
                            UpdateStatus(EmailStatus.Complete, email);

                            // Log each email being forwarded for traceability
                            // ConfigLogger.Instance.LogInfo(email.EmailID, escalate ? String.Format("Email escalated to {0}.", String.Join(" AND ", message.To.Select(a => a.GetAddressOrDisplayName()))) : "Email rejected as per defined error template.");
                        }
                        catch (Exception e)
                        {
                            ConfigLogger.Instance.LogError(email.EmailID, e);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ConfigLogger.Instance.LogError("EmailMonitor", e);
            }
        }
Ejemplo n.º 10
0
        private void ErrorRejectionAndEscalation()
        {
            try
            {
                // Get available emails
                var emails = GetErrorEmails();

                // Process any emails
                if (emails.Any())
                {
                    // Get the SMTP config from app config
                    var smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;

                    // Setup the SmtpClient to send the error emails out with
                    using (var smtp = new SmtpClient(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)))
                    {
                        // Set the timeout to 1 minute
                        smtp.Timeout = 60000;

                        // Return the emails in error
                        foreach (var email in emails)
                        {
                            if (!timer.Enabled)
                            {
                                break;
                            }

                            try
                            {
                                // Get the mailbox required for the conversion
                                var profile = Settings.MailboxProfiles[email.MailboxGUID.Value];

                                String      from    = null;
                                MailMessage message = null;

                                // If there are any errors with an action of Escalate then escalate these as opposed to rejecting
                                var escalate = (email.Errors != null && email.Errors.Descendants("Error").Any(e => (String)e.Attribute("action") == "Escalate")) ||
                                               (String.IsNullOrWhiteSpace(profile.TemplateTo) && String.IsNullOrWhiteSpace(profile.TemplateCc) && String.IsNullOrWhiteSpace(profile.TemplateBcc));

                                // Determine if the message will exceed the smtp size limit
                                var oversize = (new FileInfo(email.MessageFilePath)).Length > Settings.SmtpSizeLimit;

                                // Get the from address
                                if (!String.IsNullOrWhiteSpace(profile.TemplateFrom) && !escalate)
                                {
                                    from = profile.TemplateFrom;
                                }
                                else if (!String.IsNullOrWhiteSpace(smtpSection.From))
                                {
                                    from = smtpSection.From;
                                }
                                else
                                {
                                    from = "Decipha Email Import <*****@*****.**>";
                                }

                                MailMessage error = null;

                                try
                                {
                                    if (!oversize)
                                    {
                                        try
                                        {
                                            var options = new MailMessageLoadOptions();
                                            options.FileCompatibilityMode = FileCompatibilityMode.SkipValidityChecking;
                                            options.MessageFormat         = email.MessageFilePath.ToLower().EndsWith("msg") ? MessageFormat.Msg : MessageFormat.Eml;

                                            error = MailMessage.Load(email.MessageFilePath, options);
                                        }
                                        catch
                                        { }
                                    }

                                    if (profile.ForwardAsAttachment || escalate || oversize || error == null)
                                    {
                                        // Create a new MailMessage
                                        message = new MailMessage();

                                        // Set the from address
                                        message.From = from;

                                        if (escalate || oversize || error == null)
                                        {
                                            message.To.Add(String.IsNullOrWhiteSpace(profile.EscalationEmail) ? Settings.DefaultEscalationEmail : profile.EscalationEmail);
                                            message.Subject = String.Format("ESCALATION: Unable to process email (EmailID = {0})", email.EmailID);
                                        }
                                        else
                                        {
                                            // Set To, Cc and Bcc recipients
                                            if (!String.IsNullOrWhiteSpace(profile.TemplateTo))
                                            {
                                                message.To.Add(profile.TemplateTo);
                                            }

                                            if (!String.IsNullOrWhiteSpace(profile.TemplateCc))
                                            {
                                                message.CC.Add(profile.TemplateCc);
                                            }

                                            if (!String.IsNullOrWhiteSpace(profile.TemplateBcc))
                                            {
                                                message.Bcc.Add(profile.TemplateBcc);
                                            }

                                            // Set the subject
                                            message.Subject = String.IsNullOrWhiteSpace(profile.TemplateSubject) ? "Unable to process email..." : profile.TemplateSubject;
                                        }

                                        // Set the body
                                        if (oversize)
                                        {
                                            message.HtmlBody = AddReasonsToHtml(GetEscalationBodyHtml(profile.Description, "not attached due to SMTP size limit"), email.Errors);
                                        }
                                        else if (error == null)
                                        {
                                            message.HtmlBody = AddReasonsToHtml(GetEscalationBodyHtml(profile.Description, "not attached as the message failed to load"), email.Errors);
                                        }
                                        else if (escalate)
                                        {
                                            message.HtmlBody = AddReasonsToHtml(GetEscalationBodyHtml(profile.Description, null), email.Errors);
                                        }
                                        else
                                        {
                                            message.HtmlBody = AddReasonsToHtml(profile.TemplateBodyHtml, email.Errors);
                                        }

                                        message.IsBodyHtml = true;

                                        // Attach the error email to the template message if not over the smtp size limit
                                        if (!oversize && error != null)
                                        {
                                            error.ForwardAsAttachment(message);
                                        }
                                    }
                                    else
                                    {
                                        // Get the html body
                                        var htmlBody = AddReasonsToHtml(profile.TemplateBodyHtml, email.Errors);

                                        // Get the message for inline forwarding
                                        message = error.Forward(from, profile.TemplateTo, profile.TemplateCc, profile.TemplateBcc, htmlBody);

                                        // Override the subject if defined
                                        if (!String.IsNullOrWhiteSpace(profile.TemplateSubject))
                                        {
                                            message.Subject = profile.TemplateSubject;
                                        }
                                    }

                                    // Send the message synchronously
                                    smtp.Send(message);
                                }
                                finally
                                {
                                    if (error != null)
                                    {
                                        error.Dispose();
                                    }
                                }

                                // Update the status to Forward
                                UpdateStatus(escalate ? EmailStatus.Escalated : EmailStatus.Rejected, email);

                                // Log each email being forwarded for traceability
                                ConfigLogger.Instance.LogInfo(email.EmailID, escalate ? String.Format("Email escalated to {0}.", String.Join(" AND ", message.To.Select(a => a.GetAddressOrDisplayName()))) : "Email rejected as per defined error template.");
                            }
                            catch (Exception e)
                            {
                                ConfigLogger.Instance.LogError(email.EmailID, e);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ConfigLogger.Instance.LogError("EmailMonitor", e);
            }
        }
Ejemplo n.º 11
0
        private void ExtractAttachments(AttachmentCollection attachments)
        {
            // Add all of the attachments
            foreach (Attachment attachment in attachments)
            {
                // If the attachment is an embedded MailMessage, process it
                if (attachment.IsEmbeddedMessage())
                {
                    var options = new MailMessageLoadOptions()
                    {
                        FileCompatibilityMode = FileCompatibilityMode.SkipValidityChecking,
                        MessageFormat         = MessageFormat.Eml
                    };

                    ExtractDocuments(attachment.GetEmbeddedMessage(options), true);

                    continue;
                }

                // Get the safe filename
                var safeFile = attachment.GetSafeFileName();

                // Get the filetype (if exists)
                var fileType = profile.FileTypes.FirstOrDefault(f => Regex.IsMatch(safeFile, f.Pattern ?? string.Empty, RegexOptions.IgnoreCase));

                // Ignore the attachment if specified
                if (fileType != null && fileType.Ignore.GetValueOrDefault())
                {
                    continue;
                }

                // Extract archives if not set to passthrough
                if (fileType == null || fileType.Passthrough.GetValueOrDefault() == false)
                {
                    // Get the extension (either actual or process as extension)
                    var extension = Path.GetExtension(safeFile).TrimStart('.').ToLower();

                    // If the attachment is a zip file then extract each of the attachments
                    if (extension == "zip")
                    {
                        ExtractZip(attachment.ContentStream, safeFile);
                        continue;
                    }

                    // TODO: ADD SUPPORT FOR RAR & 7ZIP

                    // If the attachment is an embedded email, load and extract it
                    if (extension == "eml" || extension == "msg")
                    {
                        ExtractMessage(attachment.ContentStream, safeFile, extension);
                        continue;
                    }
                }

                // Otherwise, save the attachment
                String file = GetAttachmentFileName(safeFile);
                attachment.Save(file);
                File.SetAttributes(file, FileAttributes.Normal);
                Documents.Add(new Document(file, safeFile, SaveToPath, batchNumber, emailID, DocumentSource.Attachment));
            }
        }
Ejemplo n.º 12
0
        private Boolean UploadMessage(String fileName, MailboxProfile profile, String storagePath)
        {
            var options = new MailMessageLoadOptions();

            options.FileCompatibilityMode = FileCompatibilityMode.SkipValidityChecking;
            options.MessageFormat         = fileName.ToLower().EndsWith("msg") ? MessageFormat.Msg : MessageFormat.Eml;

            using (MailMessage message = MailMessage.Load(fileName, options))
                using (EmailImportDataContext ctx = new EmailImportDataContext())
                {
                    // Truncate the subject to avoid data commit errors
                    message.Subject = Truncate(message.Subject, 500);

                    if (!IsDuplicate(ctx, profile.MailboxGUID, message))
                    {
                        // Create an instance of the email database object
                        var email = new Email();

                        // Assign properties
                        email.MailboxGUID  = profile.MailboxGUID;
                        email.DateSent     = message.DateSent();
                        email.DateReceived = message.DateReceived();
                        email.From         = message.From.GetAddressOrDisplayName();
                        email.MessageID    = message.MessageId;
                        if (ExistsCCNumber(message.Subject))
                        {
                            email.Subject = MaskCCNumbers(message.Subject, '#');
                        }
                        else
                        {
                            email.Subject = message.Subject;
                        }
                        email.Timestamp = DateTime.Now;

                        // Create the dated storage path
                        var path = Path.Combine(storagePath, email.Timestamp.Value.ToString("yyyyMMdd"));

                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        // Insert the new record
                        ctx.Emails.InsertOnSubmit(email);

                        // Submit the email (we need to get the email ID)
                        using (TransactionScope scope = new TransactionScope())
                        {
                            // Initial submit of changes
                            ctx.SubmitChanges();

                            // Build the mail message file name
                            email.MessageFilePath = Path.Combine(path, String.Format("{0:00000000}.eml", email.EmailID));

                            // Copy the eml file if its already in this format, if msg then save as eml
                            if (fileName.EndsWith("eml", StringComparison.OrdinalIgnoreCase))
                            {
                                File.Copy(fileName, email.MessageFilePath, true);
                            }
                            else
                            {
                                // Save in eml format
                                message.Save(email.MessageFilePath, MessageFormat.Eml);
                            }

                            // Get the batch number - THIS SHOULD NEVER HAPPEN IN A MULTI THREAD SCENARIO WITHOUT A LOCK
                            var batchNumber = ctx.BatchNumbers.SingleOrDefault(b => b.Group == profile.Group);

                            // If there is no batchNumber defined yet, create and insert one
                            if (batchNumber == null)
                            {
                                batchNumber       = new BatchNumber();
                                batchNumber.Group = profile.Group;
                                ctx.BatchNumbers.InsertOnSubmit(batchNumber);
                            }

                            // Init to 0 if null
                            if (!batchNumber.Value.HasValue)
                            {
                                batchNumber.Value = 0;
                            }

                            // Set the new batch number to this email
                            email.BatchNumber = String.Format(String.IsNullOrWhiteSpace(profile.BatchNumberFormat) ? "{0:00000000}" : profile.BatchNumberFormat, ++batchNumber.Value);

                            // Final submit of updates
                            ctx.SubmitChanges();

                            // Finally, commit to the database
                            scope.Complete();
                        }

                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
        }