public static void Run()
        {
            // The path to the File directory.
            // ExStart:SearchStringInPSTWithIgnoreCaseParameter
            string dataDir = RunExamples.GetDataDir_Outlook();

            string path = dataDir + "SearchStringInPSTWithIgnoreCaseParameter_out.pst";

            if (File.Exists(path))
            {
                File.Delete(path);
            }


            using (PersonalStorage personalStorage = PersonalStorage.Create(dataDir + "SearchStringInPSTWithIgnoreCaseParameter_out.pst", FileFormatVersion.Unicode))
            {
                FolderInfo folderInfo = personalStorage.CreatePredefinedFolder("Inbox", StandardIpmFolder.Inbox);

                folderInfo.AddMessage(MapiMessage.FromMailMessage(MailMessage.Load(dataDir + "Message.eml")));

                PersonalStorageQueryBuilder builder = new PersonalStorageQueryBuilder();
                // IgnoreCase is True
                builder.From.Contains("automated", true);

                MailQuery             query = builder.GetQuery();
                MessageInfoCollection coll  = folderInfo.GetContents(query);
                Console.WriteLine(coll.Count);
            }
            // ExEnd:SearchStringInPSTWithIgnoreCaseParameter
        }
        Response ConvertMailToOst(string fileName, string folderName)
        {
            return(ProcessTask(fileName, folderName, delegate(string inFilePath, string outPath)
            {
                var msg = MapiHelper.GetMailMessageFromFile(inFilePath);
                var temporaryPstFileName = Path.Combine(outPath, Path.GetFileNameWithoutExtension(fileName) + ".pst");

                try
                {
                    using (var personalStorage = PersonalStorage.Create(temporaryPstFileName, FileFormatVersion.Unicode))
                    {
                        var inbox = personalStorage.RootFolder.AddSubFolder("Inbox");

                        inbox.AddMessage(MapiMessage.FromMailMessage(msg, MapiConversionOptions.UnicodeFormat));

                        var ostFileName = Path.Combine(outPath, Path.GetFileNameWithoutExtension(fileName) + ".ost");
                        personalStorage.SaveAs(ostFileName, FileFormat.Ost);
                    }
                }
                finally
                {
                    if (System.IO.File.Exists(temporaryPstFileName))
                    {
                        System.IO.File.Delete(temporaryPstFileName);
                    }
                }
            }));
        }
Exemplo n.º 3
0
        public static void Run()
        {
            // ExStart:DraftAppointmentRequest
            // The path to the File directory.
            string dataDir  = RunExamples.GetDataDir_Email();
            string dstDraft = dataDir + "appointment-draft_out.msg";

            string sender    = "*****@*****.**";
            string recipient = "*****@*****.**";

            MailMessage message = new MailMessage(sender, recipient, string.Empty, string.Empty);

            Appointment app = new Appointment(string.Empty, DateTime.Now, DateTime.Now, sender, recipient)
            {
                MethodType = AppointmentMethodType.Publish
            };

            message.AddAlternateView(app.RequestApointment());

            MapiMessage msg = MapiMessage.FromMailMessage(message);

            // Save the appointment as draft.
            msg.Save(dstDraft);

            Console.WriteLine(Environment.NewLine + "Draft saved at " + dstDraft);
            // ExEnd:DraftAppointmentRequest
        }
        public static void Run()
        {
            // The path to the File directory.
            string dataDir  = RunExamples.GetDataDir_Email();
            string dstEmail = dataDir + "New-Draft.msg";

            // Create a new instance of MailMessage class
            MailMessage message = new MailMessage();

            // Set sender information
            message.From = "*****@*****.**";

            // Add recipients
            message.To.Add("*****@*****.**");
            message.To.Add("*****@*****.**");

            // Set subject of the message
            message.Subject = "New message created by Aspose.Email";

            // Set Html body of the message
            message.IsBodyHtml = true;
            message.HtmlBody   = "<b>This line is in bold.</b> <br/> <br/><font color=blue>This line is in blue color</font>";

            // Create an instance of MapiMessage and load the MailMessag instance into it
            MapiMessage mapiMsg = MapiMessage.FromMailMessage(message);

            // Set the MapiMessageFlags as UNSENT and FROMME
            mapiMsg.SetMessageFlags(MapiMessageFlags.MSGFLAG_UNSENT | MapiMessageFlags.MSGFLAG_FROMME);

            // Save the MapiMessage to disk
            mapiMsg.Save(dstEmail);

            Console.WriteLine(Environment.NewLine + "Created draft MSG at " + dstEmail);
        }
Exemplo n.º 5
0
        public static void Run()
        {
            // ExStart:CreateDraftAppointmentFromText
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_KnowledgeBase();
            string ical    = @"BEGIN:VCALENDAR
METHOD:PUBLISH
PRODID:-//Aspose Ltd//iCalender Builder (v3.0)//EN
VERSION:2.0
BEGIN:VEVENT
ATTENDEE;[email protected]:mailto:[email protected]
DTSTART:20130220T171439
DTEND:20130220T174439
DTSTAMP:20130220T161439Z
END:VEVENT
END:VCALENDAR";

            string        sender    = "*****@*****.**";
            string        recipient = "*****@*****.**";
            MailMessage   message   = new MailMessage(sender, recipient, string.Empty, string.Empty);
            AlternateView av        = AlternateView.CreateAlternateViewFromString(ical, new ContentType("text/calendar"));

            message.AlternateViews.Add(av);
            MapiMessage msg = MapiMessage.FromMailMessage(message);

            msg.Save(dataDir + "DraftAppointmentFromText_out.msg");
            // ExEnd:CreateDraftAppointmentFromText
        }
Exemplo n.º 6
0
        public static void Run()
        {
            // ExStart:GetTheTextAndRTFBodies
            string dataDir = RunExamples.GetDataDir_Outlook();

            // Load mail message
            MapiMessage msg = MapiMessage.FromMailMessage(dataDir + "Message.eml");

            MapiMessageItemBase itemBase = new MapiMessage();

            // Text body
            if (itemBase.Body != null)
            {
                Console.WriteLine(msg.Body);
            }
            else
            {
                Console.WriteLine("There's no text body.");
            }

            // RTF body
            if (itemBase.BodyRtf != null)
            {
                Console.WriteLine(msg.BodyRtf);
            }
            else
            {
                Console.WriteLine("There's no RTF body.");
            }
            // ExEnd:GetTheTextAndRTFBodies
        }
Exemplo n.º 7
0
        public static void Run()
        {
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_Outlook();
            string dst     = dataDir + "message.msg";

            // Create an instance of MailMessage class
            MailMessage mailMsg = new MailMessage();

            // Set FROM field of the message
            mailMsg.From = "*****@*****.**";

            // Set TO field of the message
            mailMsg.To.Add("*****@*****.**");

            // Set SUBJECT of the message
            mailMsg.Subject = "creating an outlook message file";

            // Set BODY of the message
            mailMsg.Body = "This message is created by Aspose.Email";

            // Create an instance of MapiMessage class and pass MailMessage as argument
            MapiMessage outlookMsg = MapiMessage.FromMailMessage(mailMsg);

            // Save the message (msg) file
            outlookMsg.Save(dst);

            Console.WriteLine(Environment.NewLine + "MSG saved successfully at " + dst);
        }
Exemplo n.º 8
0
        public static void Run()
        {
            //ExStart:ReadAndWritingOutlookTemplateFile
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_Outlook();

            // Load the Outlook template (OFT) file in MailMessage's instance
            MailMessage message = MailMessage.Load(dataDir + "sample.oft", new MsgLoadOptions());

            // Set the sender and recipients information
            string senderDisplayName     = "John";
            string senderEmailAddress    = "*****@*****.**";
            string recipientDisplayName  = "William";
            string recipientEmailAddress = "*****@*****.**";

            message.Sender = new MailAddress(senderEmailAddress, senderDisplayName);
            message.To.Add(new MailAddress(recipientEmailAddress, recipientDisplayName));
            message.HtmlBody = message.HtmlBody.Replace("DisplayName", "<b>" + recipientDisplayName + "</b>");

            // Set the name, location and time in email body
            string meetingLocation = "<u>" + "Hall 1, Convention Center, New York, USA" + "</u>";
            string meetingTime     = "<u>" + "Monday, June 28, 2010" + "</u>";

            message.HtmlBody = message.HtmlBody.Replace("MeetingPlace", meetingLocation);
            message.HtmlBody = message.HtmlBody.Replace("MeetingTime", meetingTime);

            // Save the message in MSG format and open in Office Outlook
            MapiMessage msg = MapiMessage.FromMailMessage(message);

            msg.SetMessageFlags(MapiMessageFlags.MSGFLAG_UNSENT);
            msg.Save(dataDir + "ReadAndWritingOutlookTemplateFile_out.msg");
            //ExEnd:ReadAndWritingOutlookTemplateFile
        }
Exemplo n.º 9
0
        public static void Run()
        {
            // ExStart:ConvertMIMEMessagesFromMSGToEML
            // The path to the File directory.
            string      dataDir = RunExamples.GetDataDir_Outlook();
            MailMessage msg     = MailMessage.Load(dataDir + "message.eml");
            MapiMessage mapi    = MapiMessage.FromMailMessage(msg, new MapiConversionOptions(OutlookMessageFormat.Unicode));

            // Save File to disk
            mapi.Save(dataDir + "ConvertMIMEMessagesFromMSGToEML_out.msg");
            // ExEnd:ConvertMIMEMessagesFromMSGToEML
        }
        public static void Run()
        {
            string dataDir  = RunExamples.GetDataDir_Outlook();
            string fileName = dataDir + "message.msg";

            // ExStart:SetBodyCompression
            MailMessage           message = MailMessage.Load(fileName);
            MapiConversionOptions options = new MapiConversionOptions();

            options.UseBodyCompression = true;
            MapiMessage ae_mapi = MapiMessage.FromMailMessage(message, options);
            // ExEnd:SetBodyCompression
        }
        Response ConvertMailToPst(string fileName, string folderName)
        {
            return(ProcessTask(fileName, folderName, delegate(string inFilePath, string outPath)
            {
                var msg = MapiHelper.GetMailMessageFromFile(inFilePath);
                var pstFileName = Path.Combine(outPath, Path.GetFileNameWithoutExtension(fileName) + ".pst");

                using (var personalStorage = PersonalStorage.Create(pstFileName, FileFormatVersion.Unicode))
                {
                    var inbox = personalStorage.RootFolder.AddSubFolder("Inbox");

                    inbox.AddMessage(MapiMessage.FromMailMessage(msg, MapiConversionOptions.UnicodeFormat));
                }
            }));
        }
        public static void Run()
        {
            //ExStart: PreservingEmbeddedMsgFormat
            string dataDir = RunExamples.GetDataDir_Email();

            var eml = MailMessage.Load(dataDir + "sample.eml", new EmlLoadOptions());

            var options = MapiConversionOptions.UnicodeFormat;

            //Preserve Embedded Message Format
            options.PreserveEmbeddedMessageFormat = true;

            //Convert EML to MSG with Options
            var msg = MapiMessage.FromMailMessage(eml, options);
            //ExEnd: PreservingEmbeddedMsgFormat
        }
Exemplo n.º 13
0
 public static void Run()
 {
     // ExStart:SignAMessage
     // The path to the File directory.
     string           dataDir         = RunExamples.GetDataDir_SMTP();
     string           publicCertFile  = dataDir + "MartinCertificate.cer";
     string           privateCertFile = dataDir + "MartinCertificate.pfx";
     X509Certificate2 publicCert      = new X509Certificate2(publicCertFile);
     X509Certificate2 privateCert     = new X509Certificate2(privateCertFile, "password");
     MailMessage      msg             = new MailMessage("*****@*****.**", "*****@*****.**", "Signed message only", "Test Body of signed message");
     MailMessage      signed          = msg.AttachSignature(privateCert);
     MailMessage      encrypted       = signed.Encrypt(publicCert);
     MailMessage      decrypted       = encrypted.Decrypt(privateCert);
     MailMessage      unsigned        = decrypted.RemoveSignature();//The original message with proper body
     MapiMessage      mapi            = MapiMessage.FromMailMessage(unsigned);
     // ExEnd:SignAMessage
 }
        private void button3_Click(object sender, EventArgs e)
        {
            string dataDir = RunExamples.GetDataDir_Outlook();

            // ExStart:AddingMSGAttachments
            // File name for output MSG file
            string strMsgFile;

            // Open a save file dialog for saving the file and Add filter for msg files
            SaveFileDialog fd = new SaveFileDialog();

            fd.Filter = "Outlook Message files (*.msg)|*.msg|All files (*.*)|*.*";

            // If user pressed OK, save the file name + path
            if (fd.ShowDialog() == DialogResult.OK)
            {
                strMsgFile = fd.FileName;
            }
            else
            {
                // If user did not selected the file, return
                return;
            }

            // Create an instance of MailMessage class
            MailMessage mailMsg = new MailMessage();

            // Set from, to, subject and body properties
            mailMsg.From    = txtFrom.Text;
            mailMsg.To      = txtTo.Text;
            mailMsg.Subject = txtSubject.Text;
            mailMsg.Body    = txtBody.Text;

            // Add the attachments
            foreach (string strFileName in lstAttachments.Items)
            {
                mailMsg.Attachments.Add(new Attachment(strFileName));
            }

            // Create an instance of MapiMessage class and pass MailMessage as argument
            MapiMessage outlookMsg = MapiMessage.FromMailMessage(mailMsg);

            outlookMsg.Save(strMsgFile);
            // ExEnd:AddingMSGAttachments
        }
Exemplo n.º 15
0
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Outlook();

            // ExStart:CreatingMSGFilesWithRTFBody
            // Create an instance of the MailMessage class
            MailMessage mailMsg = new MailMessage();

            // Set from, to, subject and body properties
            mailMsg.From     = "*****@*****.**";
            mailMsg.To       = "*****@*****.**";
            mailMsg.Subject  = "subject";
            mailMsg.HtmlBody = "<h3>rtf example</h3><p>creating an <b><u>outlook message (msg)</u></b> file using Aspose.Email.</p>";

            MapiMessage outlookMsg = MapiMessage.FromMailMessage(mailMsg);

            outlookMsg.Save(dataDir + "CreatingMSGFilesWithRTFBody_out.msg");
            // ExEnd:CreatingMSGFilesWithRTFBody
        }
Exemplo n.º 16
0
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Outlook();

            // Load Microsoft Outlook email message file
            MapiMessage msg = MapiMessage.FromMailMessage(dataDir + "Message.eml");

            // Obtain subject of the email message, SenderName, body and attachments count
            Console.WriteLine("Subject:" + msg.Subject);
            Console.WriteLine("From:" + msg.SenderName);
            Console.WriteLine("Body:" + msg.Body);
            Console.WriteLine("Attachment Count:" + msg.Attachments.Count);

            // Iterate through the attachments
            foreach (MapiAttachment attachment in msg.Attachments)
            {
                Console.WriteLine("Attachment:" + attachment.FileName);
                attachment.Save(attachment.LongFileName);
            }
        }
        // ExStart:GeneratingOccurrencesFromRecurrencePatterns
        public static void GetOccurences()
        {
            // The path to the File directory
            string        dataDir       = RunExamples.GetDataDir_KnowledgeBase();
            string        tempFileName  = dataDir + "Sample.pst";
            Appointment   appointment   = CreateAppointment();
            MailMessage   mailMessage   = CreateMessage();
            AlternateView alternateView = appointment.RequestApointment();

            mailMessage.AddAlternateView(alternateView);
            MapiMessage mapiMessage = MapiMessage.FromMailMessage(mailMessage);

            using (PersonalStorage pst = PersonalStorage.Create(tempFileName, FileFormatVersion.Unicode))
            {
                FolderInfo folder = pst.RootFolder.AddSubFolder("Calendar");
                folder.AddMessage(mapiMessage);
            }

            using (PersonalStorage pst = PersonalStorage.FromFile(tempFileName))
            {
                var folder = pst.RootFolder.GetSubFolder("Calendar");
                foreach (MessageInfo messageInfo in folder.GetContents())
                {
                    MapiMessage  message = pst.ExtractMessage(messageInfo);
                    MapiCalendar meeting = (MapiCalendar)message.ToMapiMessageItem();
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        meeting.Save(memoryStream);
                        string             s = StreamToString(memoryStream);
                        CalendarRecurrence recurrencePattern = new CalendarRecurrence(s);
                        DateCollection     occurrences       = recurrencePattern.GenerateOccurrences();
                        foreach (DateTime occurrence in occurrences)
                        {
                            Console.WriteLine("{0}", occurrence);
                        }
                    }
                }
            }

            File.Delete(tempFileName);
        }
        // Gets attachment's named property
        // Property name is "CustomAttGuid"
        private static string GetNamedPropertyByAspose()
        {
            //ExStart:ReadingNamedMAPIPropertyFromAttachment
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_Outlook();

            // Load from file
            MailMessage mail = MailMessage.Load(dataDir + "outputAttachments.msg");

            var mapi = MapiMessage.FromMailMessage(mail);

            foreach (MapiNamedProperty namedProperty in mapi.Attachments[0].NamedProperties.Values)
            {
                if (string.Compare(namedProperty.NameId, "CustomAttGuid", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return(namedProperty.GetString());
                }
            }
            return(string.Empty);
            //ExEnd:ReadingNamedMAPIPropertyFromAttachment
        }
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Outlook();

            // ExStart:SavingMessageInDraftStatus
            // Change properties of an existing MSG file
            string strExistingMsg = @"message.msg";

            // Load the existing file in MailMessage and Change the properties
            MailMessage msg = MailMessage.Load(dataDir + strExistingMsg, new MsgLoadOptions());

            msg.Subject  += "NEW SUBJECT (updated by Aspose.Email)";
            msg.HtmlBody += "NEW BODY (udpated by Aspose.Email)";

            // Create an instance of type MapiMessage from MailMessage, Set message flag to un-sent (draft status) and Save it
            MapiMessage mapiMsg = MapiMessage.FromMailMessage(msg);

            mapiMsg.SetMessageFlags(MapiMessageFlags.MSGFLAG_UNSENT);
            mapiMsg.Save(dataDir + "SavingMessageInDraftStatus_out.msg");
            // ExEnd:SavingMessageInDraftStatus
        }
        public static void Run()
        {
            // The path to the File directory.
            // ExStart:CreateNewMapiCalendarAndAddToCalendarSubfolder
            string dataDir = RunExamples.GetDataDir_Outlook();

            MapiMessage mapiMessage = MapiMessage.FromMailMessage(dataDir + "Note.msg");

            // Note #1
            MapiNote note1 = (MapiNote)mapiMessage.ToMapiMessageItem();

            note1.Subject = "Yellow color note";
            note1.Body    = "This is a yellow color note";

            // Note #2
            MapiNote note2 = (MapiNote)mapiMessage.ToMapiMessageItem();

            note2.Subject = "Pink color note";
            note2.Body    = "This is a pink color note";
            note2.Color   = NoteColor.Pink;

            // Note #3
            MapiNote note3 = (MapiNote)mapiMessage.ToMapiMessageItem();

            note2.Subject = "Blue color note";
            note2.Body    = "This is a blue color note";
            note2.Color   = NoteColor.Blue;
            note3.Height  = 500;
            note3.Width   = 500;

            using (PersonalStorage pst = PersonalStorage.Create(dataDir + "SampleNote_out.pst", FileFormatVersion.Unicode))
            {
                FolderInfo notesFolder = pst.CreatePredefinedFolder("Notes", StandardIpmFolder.Notes);
                notesFolder.AddMapiMessageItem(note1);
                notesFolder.AddMapiMessageItem(note2);
                notesFolder.AddMapiMessageItem(note3);
            }
            // ExEnd:CreateNewMapiCalendarAndAddToCalendarSubfolder
        }
Exemplo n.º 21
0
        public static void Run()
        {
            // ExStart:AddAudioReminderToCalendar
            // The path to the File directory.
            string      dataDir = RunExamples.GetDataDir_Outlook();
            Appointment app     = new Appointment("Home", DateTime.Now.AddHours(1), DateTime.Now.AddHours(1), "*****@*****.**", "*****@*****.**");

            MailMessage msg = new MailMessage();

            msg.AddAlternateView(app.RequestApointment());
            MapiMessage  mapi     = MapiMessage.FromMailMessage(msg);
            MapiCalendar calendar = (MapiCalendar)mapi.ToMapiMessageItem();

            // Set calendar properties
            calendar.ReminderSet           = true;
            calendar.ReminderDelta         = 58;//58 min before start of event
            calendar.ReminderFileParameter = dataDir + "Alarm01.wav";
            string savedFile = (dataDir + "calendarWithAudioReminder_out.ics");

            calendar.Save(savedFile, AppointmentSaveFormat.Ics);
            // ExEnd:AddAudioReminderToCalendar
        }
        public static void Run()
        {
            //ExStart:SetFollowUpflag
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_Outlook();

            MailMessage mailMsg = new MailMessage();

            mailMsg.Sender = "*****@*****.**";
            mailMsg.To     = "*****@*****.**";
            mailMsg.Body   = "This message will test if follow up options can be added to a new mapi message.";
            MapiMessage mapi = MapiMessage.FromMailMessage(mailMsg);

            DateTime dtStartDate    = new DateTime(2013, 5, 23, 14, 40, 0);
            DateTime dtReminderDate = new DateTime(2013, 5, 23, 16, 40, 0);
            DateTime dtDueDate      = dtReminderDate.AddDays(1);

            FollowUpOptions options = new FollowUpOptions("Follow Up", dtStartDate, dtDueDate, dtReminderDate);

            FollowUpManager.SetOptions(mapi, options);
            mapi.Save(dataDir + "SetFollowUpflag_out.msg");
            //ExEnd:SetFollowUpflag
        }
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Outlook();

            // ExStart:CreatingAndSavingOutlookMessages
            // Create an instance of the MailMessage class
            MailMessage mailMsg = new MailMessage();

            // Set from, to, subject and body properties
            mailMsg.From    = "*****@*****.**";
            mailMsg.To      = "*****@*****.**";
            mailMsg.Subject = "This is test message";
            mailMsg.Body    = "This is test body";

            // Create an instance of the MapiMessage class and pass MailMessage as argument
            MapiMessage outlookMsg = MapiMessage.FromMailMessage(mailMsg);

            // Save the message (MSG) file
            string strMsgFile = @"CreatingAndSavingOutlookMessages_out.msg";

            outlookMsg.Save(dataDir + strMsgFile);
            // ExEnd:CreatingAndSavingOutlookMessages
        }
Exemplo n.º 24
0
        public static void Run()
        {
            // ExStart:SetFollowUpForRecipients
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_Outlook();

            MailMessage mailMsg = new MailMessage();

            mailMsg.Sender = "*****@*****.**";
            mailMsg.To     = "*****@*****.**";
            mailMsg.Body   = "This message will test if follow up options can be added to a new mapi message.";

            MapiMessage mapi = MapiMessage.FromMailMessage(mailMsg);

            mapi.SetMessageFlags(MapiMessageFlags.MSGFLAG_UNSENT);  // Mark this message as draft

            DateTime dtReminderDate = new DateTime(2013, 5, 23, 16, 40, 0);

            // Add the follow up flag for receipient now
            FollowUpManager.SetFlagForRecipients(mapi, "Follow up", dtReminderDate);
            mapi.Save(dataDir + "SetFollowUpForRecipients_out.msg");
            // ExEnd:SetFollowUpForRecipients
        }
Exemplo n.º 25
0
        public static void Run()
        {
            // ExStart:1
            // Outlook directory
            string dataDir = RunExamples.GetDataDir_Outlook();

            MailMessage mailMessage = MailMessage.Load(dataDir + "TestAppointment.eml");

            MapiConversionOptions conversionOptions = new MapiConversionOptions();

            conversionOptions.Format = OutlookMessageFormat.Unicode;

            // default value for ForcedRtfBodyForAppointment is true
            conversionOptions.ForcedRtfBodyForAppointment = false;

            MapiMessage mapiMessage = MapiMessage.FromMailMessage(mailMessage, conversionOptions);

            Console.WriteLine("Body Type: " + mapiMessage.BodyType);

            mapiMessage.Save(dataDir + "TestAppointment_out.msg");
            // ExEnd:1

            Console.WriteLine("ConvertAppointmentEMLToMSGWithHTMLBody executed successfully.");
        }
Exemplo n.º 26
0
        private void genrateSpecialTestCases()
        {
            string strFrom               = textBoxFrom.Text;
            string strTo                 = textBoxTo.Text;
            string strCC                 = textBoxCC.Text;
            string strSubject            = textBoxSubject.Text;
            string strTemplate           = textBoxTemplate.Text;
            string strWorkPath           = textBoxWorkPath.Text;
            string strPreProcessedFolder = textBoxPreProcessedFolder.Text;
            string strProcessedFolder    = textBoxProcessedFolder.Text;
            string strTestcasePrefix     = textBoxTestCasePrefix.Text;
            string strLogfilePrefix      = textBoxLogfilePrefix.Text;
            string strPayloadPattern     = textBoxPayloadPattern.Text;
            int    intKeepOpen           = StrToIntDef(textBoxKeepOpen.Text, 3);

            processTimeoutInSecond = StrToIntDef(textBoxProcessTimeout.Text, 10);
            textBoxKeepOpen.Text   = intKeepOpen.ToString();
            Boolean isURLEncoded = checkBoxURLDecode.Checked;
            Boolean isAutoRun    = checkBoxAutoRun.Checked;



            timestampLogger    = new TimestampLogging(strWorkPath + "\\" + strLogfilePrefix);
            payloadsListLogger = new SimpleLogging(strWorkPath + "\\" + textBoxPayloadsListFilename.Text);
            payloadsProcessedTestcaseFilesLogger = new SimpleLogging(strWorkPath + "\\" + textBoxProcessedTestcaseFilesFilename.Text);
            //logger.log("==Begin==");

            try
            {
                caseID = 0;
                string[] arrPrefix         = UniqueTextArrayFromFile(textBoxPrefix.Text);
                string[] arrSuffix         = UniqueTextArrayFromFile(textBoxSuffix.Text);
                string[] arrFormula        = UniqueTextArrayFromFile(textBoxFormula.Text);
                string[] arrSchemes        = UniqueTextArrayFromFile(textBoxSchemes.Text);
                string[] arrTargets        = UniqueTextArrayFromFile(textBoxTargets.Text);
                string[] arrSpecialFormula = UniqueTextArrayFromFile(textBoxSpecialFormula.Text);

                string strPreProcessedFolderFullPath = strWorkPath + "\\" + strPreProcessedFolder + "\\";
                string strProcessedFolderFullPath    = strWorkPath + "\\" + strProcessedFolder + "\\";
                System.IO.Directory.CreateDirectory(strPreProcessedFolderFullPath);
                System.IO.Directory.CreateDirectory(strProcessedFolderFullPath);

                if (isURLEncoded)
                {
                    timestampLogger.log("URL Decoding...");
                    strTemplate = Uri.UnescapeDataString(strTemplate);
                }

                string strTemplateSha1Sig = SHA1FromString(strTemplate);

                int intPrefixParalDegree         = StrToIntDef(textBoxThreadPrefixHigh.Text, 1);
                int intTargetsParalDegree        = StrToIntDef(textBoxThreadTargetsHigh.Text, 2);
                int intSpecialFormulaParalDegree = StrToIntDef(textBoxThreadSpecialFormulaHigh.Text, 5);
                int intSuffixParalDegree         = StrToIntDef(textBoxThreadSuffixHigh.Text, 1);
                if (isAutoRun)
                {
                    intPrefixParalDegree         = StrToIntDef(textBoxThreadPrefixLow.Text, 1);
                    intTargetsParalDegree        = StrToIntDef(textBoxThreadTargetsLow.Text, 1);
                    intSpecialFormulaParalDegree = StrToIntDef(textBoxThreadSpecialFormulaLow.Text, 3);
                    intSuffixParalDegree         = StrToIntDef(textBoxThreadSuffixLow.Text, 1);
                }

                long totalEvents = arrPrefix.Length * arrTargets.Length * arrSpecialFormula.Length * arrSuffix.Length;
                progressBarStatus.Value = 0;
                setLabelStatus(0, totalEvents);
                ResetCaseID();

                // to kill it on timeout: http://stackoverflow.com/questions/1410602/how-do-set-a-timeout-for-a-method
                Action <object, string, string, string, int> longMethod_showCloseMoveEmail = showCloseMoveEmail;

                Parallel.ForEach(arrPrefix, new ParallelOptions {
                    MaxDegreeOfParallelism = intPrefixParalDegree
                }, (strPrefix, loopStatePrefix) =>
                {
                    Parallel.ForEach(arrTargets, new ParallelOptions {
                        MaxDegreeOfParallelism = intTargetsParalDegree
                    }, (strTarget, loopStateTargets) =>
                    {
                        Parallel.ForEach(arrSpecialFormula, new ParallelOptions {
                            MaxDegreeOfParallelism = intSpecialFormulaParalDegree
                        }, (strSpecialFormula, loopSpecialFormula) =>
                        {
                            Parallel.ForEach(arrSuffix, new ParallelOptions {
                                MaxDegreeOfParallelism = intSuffixParalDegree
                            }, (strSuffix, loopStateSuffix) =>
                            {
                                if (Interlocked.Read(ref paused) == 1)
                                {
                                    mre.WaitOne();
                                }

                                long currentCaseID = GetNextValue();
                                string strPayload  = strSpecialFormula.Replace("<$target$>", strTarget);
                                strPayload         = strPrefix + strPayload + strSuffix + currentCaseID.ToString();
                                payloadsListLogger.log(strTemplateSha1Sig + "," + strPayload);

                                string strTempTemplate = System.Text.RegularExpressions.Regex.Replace(strTemplate, strPayloadPattern, strPayload);
                                string strTempSubject  = System.Text.RegularExpressions.Regex.Replace(strSubject, strPayloadPattern, strPayload);
                                string strTempFrom     = System.Text.RegularExpressions.Regex.Replace(strFrom, strPayloadPattern, strPayload);
                                string strTempTo       = System.Text.RegularExpressions.Regex.Replace(strTo, strPayloadPattern, strPayload);
                                string strTempCC       = System.Text.RegularExpressions.Regex.Replace(strCC, strPayloadPattern, strPayload);


                                MailMessage msg = new MailMessage();

                                // Set recipients information
                                if (!String.IsNullOrEmpty(strTempFrom))
                                {
                                    msg.From = strTempFrom;
                                }
                                if (!String.IsNullOrEmpty(strTempTo))
                                {
                                    msg.To = strTempTo;
                                }
                                if (!String.IsNullOrEmpty(strTempCC))
                                {
                                    msg.CC = strTempCC;
                                }

                                // Set the subject
                                msg.Subject = strTempSubject;

                                // Set HTML body
                                msg.HtmlBody = strTempTemplate;

                                // Add an attachment
                                // msg.Attachments.Add(new Aspose.Email.Mail.Attachment("test.txt"));

                                // Local filenames
                                string strTestCaseFileName   = MakeValidFileName(strTestcasePrefix + currentCaseID.ToString() + "-" + strTempSubject + ".msg");
                                string strInProgressFilePath = strPreProcessedFolderFullPath + strTestCaseFileName;

                                //msg.Save(strFullFilePath,SaveOptions.DefaultMsg);

                                MapiMessage outlookMsg = MapiMessage.FromMailMessage(msg);
                                outlookMsg.SetMessageFlags(MapiMessageFlags.MSGFLAG_SUBMIT);


                                while (File.Exists(strInProgressFilePath))
                                {
                                    strInProgressFilePath = strPreProcessedFolderFullPath + Guid.NewGuid() + "_" + strTestCaseFileName;
                                }
                                timestampLogger.log("Saving the " + strTestCaseFileName + " file in: " + strInProgressFilePath);
                                outlookMsg.Save(strInProgressFilePath);

                                if (isAutoRun)
                                {
                                    mre.WaitOne();
                                    //showCloseMoveEmail(strInProgressFilePath, strProcessedFolderFullPath, strTestCaseFileName, intKeepOpen);

                                    // to kill it on timeout: http://stackoverflow.com/questions/1410602/how-do-set-a-timeout-for-a-method
                                    object monitorSync = new object();
                                    bool timedOut;
                                    lock (monitorSync)
                                    {
                                        longMethod_showCloseMoveEmail.BeginInvoke(monitorSync, strInProgressFilePath, strProcessedFolderFullPath, strTestCaseFileName, intKeepOpen, null, null);
                                        timedOut = !Monitor.Wait(monitorSync, TimeSpan.FromSeconds(processTimeoutInSecond));
                                    }
                                    if (timedOut)
                                    {
                                        object _lock = new object();
                                        lock (_lock)
                                        {
                                            killProcess("OUTLOOK", processTimeoutInSecond);
                                            timestampLogger.log("Process killed due to " + processTimeoutInSecond.ToString() + " seconds timeout");
                                        }
                                    }


                                    if (currentCaseID % 10 == 0 || currentCaseID == totalEvents)
                                    {
                                        setLabelStatus(currentCaseID, totalEvents);
                                    }
                                }
                                else
                                {
                                    if (currentCaseID % 100 == 0 || currentCaseID == totalEvents)
                                    {
                                        setLabelStatus(currentCaseID, totalEvents);
                                    }
                                }
                            }
                                             );
                        }
                                         );
                    }
                                     );
                }

                                 );
            }
            catch (Exception e)
            {
                timestampLogger.log("Error in genrateSpecialTestCases(): " + e.StackTrace);
                MessageBox.Show("An error occured!", "Error!");
            }
            //logger.log("==End==");
        }
Exemplo n.º 27
0
        private void genrateSampleTemplate()
        {
            string strFrom               = textBoxFrom.Text;
            string strTo                 = textBoxTo.Text;
            string strCC                 = textBoxCC.Text;
            string strSubject            = textBoxSubject.Text;
            string strTemplate           = textBoxTemplate.Text;
            string strWorkPath           = textBoxWorkPath.Text;
            string strPreProcessedFolder = textBoxPreProcessedFolder.Text;
            string strProcessedFolder    = textBoxProcessedFolder.Text;
            string strTestcasePrefix     = textBoxTestCasePrefix.Text;
            string strLogfilePrefix      = textBoxLogfilePrefix.Text;
            int    intKeepOpen           = StrToIntDef(textBoxKeepOpen.Text, 3);

            processTimeoutInSecond = StrToIntDef(textBoxProcessTimeout.Text, 10);

            textBoxKeepOpen.Text = intKeepOpen.ToString();
            Boolean isURLEncoded = checkBoxURLDecode.Checked;
            Boolean isAutoRun    = checkBoxAutoRun.Checked;

            timestampLogger = new TimestampLogging(strWorkPath + "\\" + strLogfilePrefix);
            payloadsProcessedTestcaseFilesLogger = new SimpleLogging(strWorkPath + "\\" + textBoxProcessedTestcaseFilesFilename.Text);
            //logger.log("==Begin==");

            // to kill it on timeout: http://stackoverflow.com/questions/1410602/how-do-set-a-timeout-for-a-method
            Action <object, string, string, string, int> longMethod_showCloseMoveEmail = showCloseMoveEmail;

            try
            {
                string strPreProcessedFolderFullPath = strWorkPath + "\\" + strPreProcessedFolder + "\\";
                string strProcessedFolderFullPath    = strWorkPath + "\\" + strProcessedFolder + "\\";
                System.IO.Directory.CreateDirectory(strPreProcessedFolderFullPath);
                System.IO.Directory.CreateDirectory(strProcessedFolderFullPath);

                if (isURLEncoded)
                {
                    timestampLogger.log("URL Decoding...");
                    strTemplate = Uri.UnescapeDataString(strTemplate);
                }

                MailMessage msg = new MailMessage();

                // Set recipients information
                if (!String.IsNullOrEmpty(strFrom))
                {
                    msg.From = strFrom;
                }
                if (!String.IsNullOrEmpty(strTo))
                {
                    msg.To = strTo;
                }
                if (!String.IsNullOrEmpty(strCC))
                {
                    msg.CC = strCC;
                }

                // Set the subject
                msg.Subject = strSubject;

                // Set HTML body
                msg.HtmlBody = strTemplate;

                // Add an attachment
                // msg.Attachments.Add(new Aspose.Email.Mail.Attachment("test.txt"));

                // Local filenames
                string strTestCaseFileName   = MakeValidFileName(strTestcasePrefix + strSubject + ".msg");
                string strInProgressFilePath = strPreProcessedFolderFullPath + strTestCaseFileName;

                //msg.Save(strFullFilePath,SaveOptions.DefaultMsg);

                MapiMessage outlookMsg = MapiMessage.FromMailMessage(msg);
                outlookMsg.SetMessageFlags(MapiMessageFlags.MSGFLAG_SUBMIT);


                while (File.Exists(strInProgressFilePath))
                {
                    strInProgressFilePath = strPreProcessedFolderFullPath + Guid.NewGuid() + "_" + strTestCaseFileName;
                }
                timestampLogger.log("Saving the " + strTestCaseFileName + " file in: " + strInProgressFilePath);
                outlookMsg.Save(strInProgressFilePath);

                if (isAutoRun)
                {
                    new Thread(delegate()
                    {
                        //showCloseMoveEmail(strInProgressFilePath, strProcessedFolderFullPath, strTestCaseFileName, intKeepOpen);

                        // to kill it on timeout: http://stackoverflow.com/questions/1410602/how-do-set-a-timeout-for-a-method
                        object monitorSync = new object();
                        bool timedOut;
                        lock (monitorSync)
                        {
                            longMethod_showCloseMoveEmail.BeginInvoke(monitorSync, strInProgressFilePath, strProcessedFolderFullPath, strTestCaseFileName, intKeepOpen, null, null);
                            timedOut = !Monitor.Wait(monitorSync, TimeSpan.FromSeconds(processTimeoutInSecond));
                        }
                        if (timedOut)
                        {
                            object _lock = new object();
                            lock (_lock)
                            {
                                killProcess("OUTLOOK", processTimeoutInSecond);
                                timestampLogger.log("Process killed due to " + processTimeoutInSecond.ToString() + " seconds timeout");
                            }
                        }
                    }).Start();
                }
            }
            catch (Exception e)
            {
                timestampLogger.log("Error in genrateSampleTemplate(): " + e.StackTrace);
            }
            //logger.log("==End==");
        }