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

            // Create a sample Message
            MapiMessage mapiMsg = new MapiMessage("*****@*****.**", "*****@*****.**", "This is subject", "This is body");

            // Set multiple properties
            mapiMsg.SetProperty(new MapiProperty(MapiPropertyTag.PR_SENDER_ADDRTYPE_W, Encoding.Unicode.GetBytes("EX")));
            MapiRecipient recipientTo = mapiMsg.Recipients[0];
            MapiProperty propAddressType = new MapiProperty(MapiPropertyTag.PR_RECEIVED_BY_ADDRTYPE_W, Encoding.UTF8.GetBytes("MYFAX"));
            recipientTo.SetProperty(propAddressType);
            string faxAddress = "My Fax User@/FN=fax#/VN=voice#/CO=My Company/CI=Local";
            MapiProperty propEmailAddress = new MapiProperty(MapiPropertyTag.PR_RECEIVED_BY_EMAIL_ADDRESS_W, Encoding.UTF8.GetBytes(faxAddress));
            recipientTo.SetProperty(propEmailAddress);
            mapiMsg.SetMessageFlags(MapiMessageFlags.MSGFLAG_UNSENT | MapiMessageFlags.MSGFLAG_FROMME);
            mapiMsg.SetProperty(new MapiProperty(MapiPropertyTag.PR_RTF_IN_SYNC, BitConverter.GetBytes((long)1)));

            // Set DateTime property
            MapiProperty modificationTime = new MapiProperty(MapiPropertyTag.PR_LAST_MODIFICATION_TIME, ConvertDateTime(new DateTime(2013, 9, 11)));
            mapiMsg.SetProperty(modificationTime);
            mapiMsg.Save(dataDir + "MapiProp_out.msg");
            //ExEnd:SetMAPIProperties
        }
 public static void Run()
 {
     //ExStart:ConvertMSGToMIMEMessage
     MapiMessage msg = new MapiMessage("*****@*****.**","[email protected]; [email protected]","Test Subject","This is a body of message.");
     var options = new MailConversionOptions();
     options.ConvertAsTnef = true;
     MailMessage mail = msg.ToMailMessage(options);
     //ExEnd:ConvertMSGToMIMEMessage
 }
        private static MapiMessage CreateTestMessage(bool draft)
        {
            MapiMessage msg = new MapiMessage(
            "*****@*****.**",
            "*****@*****.**",
            "Flagged message",
            "Make it nice and short, but descriptive. The description may appear in search engines' search results pages...");

            if (!draft)
            {
                msg.SetMessageFlags(msg.Flags ^ MapiMessageFlags.MSGFLAG_UNSENT);
            }

            return msg;
        }
 static void Run()
 {
     // ExStart: SaveMsgAsTemplate
     ///<summary>
     /// This example shows how to save an Outlook MSG file to Outlook Template  using the MapiMessage API
     /// Available from Aspose.Email for .NET 6.4.0 onwards
     /// MapiMessage.SaveAsTemplate(Stream stream) - Saves to the specified stream as Outlook File Template(OFT format).
     /// MapiMessage.SaveAsTemplate(string fileName) - Saves to the specified file as Outlook File Template(OFT format).
     ///</summary>
     using (MapiMessage mapi = new MapiMessage("*****@*****.**", "*****@*****.**", "template subject", "Template body"))
     {
         string oftMapiFileName = "mapiToOft.msg";
         mapi.SaveAsTemplate(oftMapiFileName);
     }            
     // ExEnd: SaveMsgAsTemplate
 }
Exemplo n.º 5
0
        public void SendMail ()
        {
            var recipients = new List<MapiRecipDesc>();
            To.ForEach(email => recipients.Add(new MapiRecipDesc { recipClass = RecipClass.To, name = email }));
            CC.ForEach(email => recipients.Add(new MapiRecipDesc { recipClass = RecipClass.CC, name = email }));
            BCC.ForEach(email => recipients.Add(new MapiRecipDesc { recipClass = RecipClass.BCC, name = email }));

            var msg = new MapiMessage {
                subject = Subject, noteText = Body,
                recips = GetRecipientsData(recipients), recipCount = recipients.Count,
                files = GetAttachmentsData(Attachments), fileCount = Attachments.Count,
            };

            int result = MAPISendMail(IntPtr.Zero, IntPtr.Zero, msg, MAPI_LOGON_UI | MAPI_DIALOG, 0);
            if (result > 1)
                throw new Exception("Failed to send mail: {0}.".Fmt(GetErrorMessage(result)));
            Cleanup(msg);
        }
        public static void Run()
        {
            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.");
        }
Exemplo n.º 7
0
        private bool SendMail(string subject, string body, SendFlags flags)
        {
            MapiMessage message = new MapiMessage();
            message.subject = subject;
            message.noteText = body;
            message.recips = GetRecipients(out message.recipCount);
            message.files = GetAttachments(out message.fileCount);

            lastError = (MessageApiError)MAPISendMail(IntPtr.Zero, IntPtr.Zero, message, flags, 0);
            Cleanup(message);
            return lastError == MessageApiError.Success;
        }
        public static bool IsInlineAttachment(MapiAttachment att, MapiMessage msg)
        {
            switch (msg.BodyType)
            {
                case BodyContentType.PlainText:
                    // ignore indications for plain text messages
                    return false;

                case BodyContentType.Html:

                    // check the PidTagAttachFlags property
                    if (att.Properties.Contains(0x37140003))
                    {
                        long? attachFlagsValue = att.GetPropertyLong(0x37140003);
                        if (attachFlagsValue != null && (attachFlagsValue & 0x00000004) == 0x00000004)
                        {
                            // check PidTagAttachContentId property
                            if (att.Properties.Contains(MapiPropertyTag.PR_ATTACH_CONTENT_ID) ||
                                att.Properties.Contains(MapiPropertyTag.PR_ATTACH_CONTENT_ID_W))
                            {
                                string contentId = att.Properties.Contains(MapiPropertyTag.PR_ATTACH_CONTENT_ID)
                                    ? att.Properties[MapiPropertyTag.PR_ATTACH_CONTENT_ID].GetString()
                                    : att.Properties[MapiPropertyTag.PR_ATTACH_CONTENT_ID_W].GetString();
                                if (msg.BodyHtml.Contains(contentId))
                                {
                                    return true;
                                }
                            }
                            // check PidTagAttachContentLocation property
                            if (att.Properties.Contains(0x3713001E) ||
                                att.Properties.Contains(0x3713001F))
                            {
                                return true;
                            }
                        }
                        else if ((att.Properties.Contains(0x3716001F) && att.GetPropertyString(0x3716001F) == "inline")
                            || (att.Properties.Contains(0x3716001E) && att.GetPropertyString(0x3716001E) == "inline"))
                        {
                            return true;
                        }
                    }
                    else if ((att.Properties.Contains(0x3716001F) && att.GetPropertyString(0x3716001F) == "inline")
                            || (att.Properties.Contains(0x3716001E) && att.GetPropertyString(0x3716001E) == "inline"))
                    {
                        return true;
                    }
                    return false;

                case BodyContentType.Rtf:

                    // If the body is RTF, then all OLE attachments are inline attachments.
                    // OLE attachments have 0x00000006 for the value of the PidTagAttachMethod property
                    if (att.Properties.Contains(MapiPropertyTag.PR_ATTACH_METHOD))
                    {
                        return att.GetPropertyLong(MapiPropertyTag.PR_ATTACH_METHOD) == 0x00000006;
                    }
                    return false;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
        int SendMail(string strSubject, string strBody, int how)
        {
            MapiMessage msg = new MapiMessage();
            msg.subject = strSubject;
            msg.noteText = strBody;

            msg.recips = GetRecipients(out msg.recipCount);
            msg.files = GetAttachments(out msg.fileCount);

            m_lastError = MAPISendMail(new IntPtr(0), new IntPtr(0),
                msg, how, 0);

            if (m_lastError > 1)
                MessageBox.Show("MAPISendMail failed! " + GetLastError(),
                    "MAPISendMail");

            Cleanup(ref msg);
            return m_lastError;
        }
Exemplo n.º 10
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.º 11
0
 private static void Cleanup(MapiMessage msg)
 {
     Native.FreeHGlobalArray <MapiRecipDesc>(msg.recips, msg.recipCount);
     Native.FreeHGlobalArray <MapiFileDesc>(msg.files, msg.fileCount);
 }
Exemplo n.º 12
0
        public ICoreItem OpenAttachedItem(ICollection <PropertyDefinition> propertiesToLoad, AttachmentPropertyBag attachmentBag, bool isNew)
        {
            MapiMessage            mapiMessage            = null;
            PersistablePropertyBag persistablePropertyBag = null;
            CoreItem      coreItem      = null;
            bool          flag          = false;
            StoreObjectId storeObjectId = null;

            byte[]    array = null;
            ICoreItem result;

            try
            {
                StoreObjectPropertyBag storeObjectPropertyBag = (StoreObjectPropertyBag)attachmentBag.PersistablePropertyBag;
                MapiAttach             mapiAttach             = (MapiAttach)storeObjectPropertyBag.MapiProp;
                StoreSession           session           = this.AttachmentCollection.ContainerItem.Session;
                OpenPropertyFlags      openPropertyFlags = isNew ? OpenPropertyFlags.Create : (this.AttachmentCollection.IsReadOnly ? OpenPropertyFlags.BestAccess : OpenPropertyFlags.BestAccess);
                openPropertyFlags |= OpenPropertyFlags.DeferredErrors;
                string text   = storeObjectPropertyBag.TryGetProperty(InternalSchema.ItemClass) as string;
                Schema schema = (text != null) ? ObjectClass.GetSchema(text) : MessageItemSchema.Instance;
                propertiesToLoad = InternalSchema.Combine <PropertyDefinition>(schema.AutoloadProperties, propertiesToLoad);
                StoreSession session2 = this.AttachmentCollection.ContainerItem.Session;
                bool         flag2    = false;
                try
                {
                    if (session2 != null)
                    {
                        session2.BeginMapiCall();
                        session2.BeginServerHealthCall();
                        flag2 = true;
                    }
                    if (StorageGlobals.MapiTestHookBeforeCall != null)
                    {
                        StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod());
                    }
                    mapiMessage = mapiAttach.OpenEmbeddedMessage(openPropertyFlags);
                }
                catch (MapiPermanentException ex)
                {
                    throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotOpenEmbeddedMessage, ex, session2, this, "{0}. MapiException = {1}.", new object[]
                    {
                        string.Format("MapiAttachmentProvider::OpenAttachedItem", new object[0]),
                        ex
                    });
                }
                catch (MapiRetryableException ex2)
                {
                    throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotOpenEmbeddedMessage, ex2, session2, this, "{0}. MapiException = {1}.", new object[]
                    {
                        string.Format("MapiAttachmentProvider::OpenAttachedItem", new object[0]),
                        ex2
                    });
                }
                finally
                {
                    try
                    {
                        if (session2 != null)
                        {
                            session2.EndMapiCall();
                            if (flag2)
                            {
                                session2.EndServerHealthCall();
                            }
                        }
                    }
                    finally
                    {
                        if (StorageGlobals.MapiTestHookAfterCall != null)
                        {
                            StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod());
                        }
                    }
                }
                persistablePropertyBag = new StoreObjectPropertyBag(session, mapiMessage, propertiesToLoad);
                if (!isNew)
                {
                    StoreObjectType storeObjectType = ItemBuilder.ReadStoreObjectTypeFromPropertyBag(persistablePropertyBag);
                    ItemCreateInfo  itemCreateInfo  = ItemCreateInfo.GetItemCreateInfo(storeObjectType);
                    propertiesToLoad = InternalSchema.Combine <PropertyDefinition>(itemCreateInfo.Schema.AutoloadProperties, propertiesToLoad);
                    if (this.AttachmentCollection.IsReadOnly)
                    {
                        StoreId.SplitStoreObjectIdAndChangeKey(StoreObjectId.DummyId, out storeObjectId, out array);
                    }
                    persistablePropertyBag = new AcrPropertyBag(persistablePropertyBag, itemCreateInfo.AcrProfile, storeObjectId, new RetryBagFactory(session), array);
                }
                coreItem = new CoreItem(session, persistablePropertyBag, storeObjectId, array, isNew ? Origin.New : Origin.Existing, ItemLevel.Attached, propertiesToLoad, ItemBindOption.None);
                if (text != null && isNew)
                {
                    coreItem.PropertyBag[InternalSchema.ItemClass] = text;
                }
                flag   = true;
                result = coreItem;
            }
            finally
            {
                if (!flag)
                {
                    if (coreItem != null)
                    {
                        coreItem.Dispose();
                        coreItem = null;
                    }
                    if (persistablePropertyBag != null)
                    {
                        persistablePropertyBag.Dispose();
                        persistablePropertyBag = null;
                    }
                    if (mapiMessage != null)
                    {
                        mapiMessage.Dispose();
                        mapiMessage = null;
                    }
                }
            }
            return(result);
        }
Exemplo n.º 13
0
        public PersistablePropertyBag CreateAttachment(ICollection <PropertyDefinition> propertiesToLoad, CoreAttachment attachmentToClone, IItem itemToAttach, out int attachmentNumber)
        {
            MapiAttach             mapiAttach             = null;
            PersistablePropertyBag persistablePropertyBag = null;
            bool flag = false;
            int  num  = 0;

            try
            {
                StoreSession session = this.AttachmentCollection.ContainerItem.Session;
                bool         flag2   = false;
                try
                {
                    if (session != null)
                    {
                        session.BeginMapiCall();
                        session.BeginServerHealthCall();
                        flag2 = true;
                    }
                    if (StorageGlobals.MapiTestHookBeforeCall != null)
                    {
                        StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod());
                    }
                    mapiAttach = this.AttachmentCollection.ContainerItem.MapiMessage.CreateAttach(out num);
                }
                catch (MapiPermanentException ex)
                {
                    throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotOpenAttachment, ex, session, this, "{0}. MapiException = {1}.", new object[]
                    {
                        string.Format("MapiAttachmentProvider::CreateMapiAttachment", new object[0]),
                        ex
                    });
                }
                catch (MapiRetryableException ex2)
                {
                    throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotOpenAttachment, ex2, session, this, "{0}. MapiException = {1}.", new object[]
                    {
                        string.Format("MapiAttachmentProvider::CreateMapiAttachment", new object[0]),
                        ex2
                    });
                }
                finally
                {
                    try
                    {
                        if (session != null)
                        {
                            session.EndMapiCall();
                            if (flag2)
                            {
                                session.EndServerHealthCall();
                            }
                        }
                    }
                    finally
                    {
                        if (StorageGlobals.MapiTestHookAfterCall != null)
                        {
                            StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod());
                        }
                    }
                }
                attachmentNumber = num;
                if (attachmentToClone != null)
                {
                    MapiAttachmentProvider.CopySavedMapiAttachment(true, this, this.AttachmentCollection.ContainerItem.Session, (MapiAttach)attachmentToClone.PropertyBag.MapiProp, mapiAttach);
                }
                else if (itemToAttach != null)
                {
                    MapiMessage  mapiMessage  = itemToAttach.MapiMessage;
                    MapiMessage  mapiMessage2 = null;
                    StoreSession session2     = this.AttachmentCollection.ContainerItem.Session;
                    bool         flag3        = false;
                    try
                    {
                        if (session2 != null)
                        {
                            session2.BeginMapiCall();
                            session2.BeginServerHealthCall();
                            flag3 = true;
                        }
                        if (StorageGlobals.MapiTestHookBeforeCall != null)
                        {
                            StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod());
                        }
                        mapiMessage2 = mapiAttach.OpenEmbeddedMessage(OpenPropertyFlags.Create);
                    }
                    catch (MapiPermanentException ex3)
                    {
                        throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotOpenEmbeddedMessage, ex3, session2, this, "{0}. MapiException = {1}.", new object[]
                        {
                            string.Format("MapiAttachmentProvider::CreateMapiAttachment", new object[0]),
                            ex3
                        });
                    }
                    catch (MapiRetryableException ex4)
                    {
                        throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotOpenEmbeddedMessage, ex4, session2, this, "{0}. MapiException = {1}.", new object[]
                        {
                            string.Format("MapiAttachmentProvider::CreateMapiAttachment", new object[0]),
                            ex4
                        });
                    }
                    finally
                    {
                        try
                        {
                            if (session2 != null)
                            {
                                session2.EndMapiCall();
                                if (flag3)
                                {
                                    session2.EndServerHealthCall();
                                }
                            }
                        }
                        finally
                        {
                            if (StorageGlobals.MapiTestHookAfterCall != null)
                            {
                                StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod());
                            }
                        }
                    }
                    using (mapiMessage2)
                    {
                        PropProblem[] array    = null;
                        StoreSession  session3 = this.AttachmentCollection.ContainerItem.Session;
                        bool          flag4    = false;
                        try
                        {
                            if (session3 != null)
                            {
                                session3.BeginMapiCall();
                                session3.BeginServerHealthCall();
                                flag4 = true;
                            }
                            if (StorageGlobals.MapiTestHookBeforeCall != null)
                            {
                                StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod());
                            }
                            array = mapiMessage.CopyTo(mapiMessage2, new PropTag[]
                            {
                                (PropTag)InternalSchema.UrlCompName.PropertyTag
                            });
                        }
                        catch (MapiPermanentException ex5)
                        {
                            throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCopyFailedProperties, ex5, session3, this, "{0}. MapiException = {1}.", new object[]
                            {
                                string.Format("MapiAttachmentProvider::CreateMapiAttachment", new object[0]),
                                ex5
                            });
                        }
                        catch (MapiRetryableException ex6)
                        {
                            throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCopyFailedProperties, ex6, session3, this, "{0}. MapiException = {1}.", new object[]
                            {
                                string.Format("MapiAttachmentProvider::CreateMapiAttachment", new object[0]),
                                ex6
                            });
                        }
                        finally
                        {
                            try
                            {
                                if (session3 != null)
                                {
                                    session3.EndMapiCall();
                                    if (flag4)
                                    {
                                        session3.EndServerHealthCall();
                                    }
                                }
                            }
                            finally
                            {
                                if (StorageGlobals.MapiTestHookAfterCall != null)
                                {
                                    StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod());
                                }
                            }
                        }
                        if (array != null)
                        {
                            int num2 = -1;
                            for (int i = 0; i < array.Length; i++)
                            {
                                int scode = array[i].Scode;
                                if (scode == -2147221233 || scode == -2147221222)
                                {
                                    ExTraceGlobals.StorageTracer.TraceDebug <int>((long)this.GetHashCode(), "Storage.MapiAttachmentProvider.AddExisting Item: CopyTo returned ignorable scode = {0}", scode);
                                }
                                else
                                {
                                    ExTraceGlobals.StorageTracer.TraceError <int>((long)this.GetHashCode(), "Storage.MapiAttachmentProvider.AddExisting Item: CopyTo returned fatal scode = {0}", scode);
                                    num2 = i;
                                }
                                if (num2 != -1)
                                {
                                    throw PropertyError.ToException(ServerStrings.ExUnableToCopyAttachments, StoreObjectPropertyBag.MapiPropProblemsToPropertyErrors(null, mapiMessage, array));
                                }
                            }
                        }
                        StoreSession session4 = this.AttachmentCollection.ContainerItem.Session;
                        bool         flag5    = false;
                        try
                        {
                            if (session4 != null)
                            {
                                session4.BeginMapiCall();
                                session4.BeginServerHealthCall();
                                flag5 = true;
                            }
                            if (StorageGlobals.MapiTestHookBeforeCall != null)
                            {
                                StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod());
                            }
                            mapiMessage2.SaveChanges();
                        }
                        catch (MapiPermanentException ex7)
                        {
                            throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotSaveChanges, ex7, session4, this, "{0}. MapiException = {1}.", new object[]
                            {
                                string.Format("MapiAttachmentProvider::CreateMapiAttachment", new object[0]),
                                ex7
                            });
                        }
                        catch (MapiRetryableException ex8)
                        {
                            throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotSaveChanges, ex8, session4, this, "{0}. MapiException = {1}.", new object[]
                            {
                                string.Format("MapiAttachmentProvider::CreateMapiAttachment", new object[0]),
                                ex8
                            });
                        }
                        finally
                        {
                            try
                            {
                                if (session4 != null)
                                {
                                    session4.EndMapiCall();
                                    if (flag5)
                                    {
                                        session4.EndServerHealthCall();
                                    }
                                }
                            }
                            finally
                            {
                                if (StorageGlobals.MapiTestHookAfterCall != null)
                                {
                                    StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod());
                                }
                            }
                        }
                    }
                }
                persistablePropertyBag            = this.CreateStorePropertyBag(mapiAttach, propertiesToLoad);
                persistablePropertyBag.ExTimeZone = this.ExTimeZone;
                flag = true;
            }
            finally
            {
                if (!flag)
                {
                    if (persistablePropertyBag != null)
                    {
                        persistablePropertyBag.Dispose();
                    }
                    if (mapiAttach != null)
                    {
                        mapiAttach.Dispose();
                    }
                }
            }
            return(persistablePropertyBag);
        }
Exemplo n.º 14
0
            int SendMail(string strSubject, string strBody, int how)
            {
                MapiMessage msg = new MapiMessage();
                msg.subject = strSubject;
                msg.noteText = strBody;

                msg.recips = GetRecipients(out msg.recipCount);
                msg.files = GetAttachments(out msg.fileCount);

                m_lastError = MAPISendMail(new IntPtr(0), new IntPtr(0), msg, how,
                    0);

                if (m_lastError > 1)
                {
                    string samp = "MAPISendMail failed! " + GetLastError() + "MAPISendMail";
                    YesNoBox yesNo = new YesNoBox(samp);
                    yesNo.ShowDialog();
                    //MessageBox.Show("MAPISendMail failed! " + GetLastError(),
                    //    "MAPISendMail");
                }
                Cleanup(ref msg);
                return m_lastError;
            }
Exemplo n.º 15
0
 public static extern uint MAPISendMail(IntPtr lhSession, IntPtr ulUIParam, MapiMessage lpMessage, uint flFlags, uint ulReserved);
Exemplo n.º 16
0
 public static extern int MAPISendMail(IntPtr session, IntPtr hwnd, MapiMessage message, int flg, int rsv);
Exemplo n.º 17
0
 private static extern int MAPISendMail(IntPtr sess, IntPtr hwnd, MapiMessage message, int flg, int rsv);
        void Cleanup(ref MapiMessage msg)
        {
            int size = Marshal.SizeOf(typeof(MapiRecipDesc));
            int ptr = 0;

            if (msg.recips != IntPtr.Zero)
            {
                ptr = (int)msg.recips;
                for (int i = 0; i < msg.recipCount; i++)
                {
                    Marshal.DestroyStructure((IntPtr)ptr,
                        typeof(MapiRecipDesc));
                    ptr += size;
                }
                Marshal.FreeHGlobal(msg.recips);
            }

            if (msg.files != IntPtr.Zero)
            {
                size = Marshal.SizeOf(typeof(MapiFileDesc));

                ptr = (int)msg.files;
                for (int i = 0; i < msg.fileCount; i++)
                {
                    Marshal.DestroyStructure((IntPtr)ptr,
                        typeof(MapiFileDesc));
                    ptr += size;
                }
                Marshal.FreeHGlobal(msg.files);
            }

            m_recipients.Clear();
            m_attachments.Clear();
            m_lastError = 0;
        }
 ///<Summary>
 /// Add Custom Property
 ///</Summary>
 /// <param name="msg"></param>
 /// <param name="name"></param>
 /// <param name="value"></param>
 public static MapiProperty AddCustomProperty(this MapiMessage msg, string name, long value)
 {
     return(msg.AddCustomProperty(name, MapiPropertyType.PT_LONG, BitConverter.GetBytes(value)));
 }
Exemplo n.º 20
0
 private static extern int MAPISendMail (IntPtr sess, IntPtr hwnd, MapiMessage message, int flg, int rsv);
 ///<Summary>
 /// Add Custom Property
 ///</Summary>
 /// <param name="msg"></param>
 /// <param name="name"></param>
 /// <param name="value"></param>
 public static MapiProperty AddCustomProperty(this MapiMessage msg, string name, string value)
 {
     return(msg.AddCustomProperty(name, MapiPropertyType.PT_UNICODE, Encoding.Unicode.GetBytes(value)));
 }
Exemplo n.º 22
0
 private static void Cleanup (MapiMessage msg)
 {
     Native.FreeHGlobalArray<MapiRecipDesc>(msg.recips, msg.recipCount);
     Native.FreeHGlobalArray<MapiFileDesc>(msg.files, msg.fileCount);
 }
Exemplo n.º 23
0
 private static extern int MAPISendMail(IntPtr session, IntPtr hWnd, MapiMessage message, SendFlags flags, uint reserved);
Exemplo n.º 24
0
        private void Cleanup(MapiMessage msg)
        {
            int size = Marshal.SizeOf(typeof(MapiRecipDesc));
            long ptr = 0;

            if (msg.recips != IntPtr.Zero)
            {
                ptr = msg.recips.ToInt64();
                for (int i = 0; i < msg.recipCount; i++)
                {
                    Marshal.DestroyStructure(new IntPtr(ptr), typeof(MapiRecipDesc));
                    ptr += size;
                }
                Marshal.FreeHGlobal(msg.recips);
            }

            if (msg.files != IntPtr.Zero)
            {
                size = Marshal.SizeOf(typeof(MapiFileDesc));

                ptr = msg.files.ToInt64();
                for (int i = 0; i < msg.fileCount; i++)
                {
                    Marshal.DestroyStructure(new IntPtr(ptr), typeof(MapiFileDesc));
                    ptr += size;
                }
                Marshal.FreeHGlobal(msg.files);
            }

            recipients.Clear();
            attachments.Clear();
        }
Exemplo n.º 25
0
 internal static extern uint MAPISendMailW(IntPtr lhSession, IntPtr ulUIParam, ref MapiMessage lpMessage, int flFlags, uint ulReserved);
Exemplo n.º 26
0
 public static extern int MAPISendMail(IntPtr session, IntPtr hwnd, MapiMessage message, int flg, int rsv);
Exemplo n.º 27
0
        /// <summary>
        /// Creates and sends an e-mail message using the Simple MAPI protocol.</summary>
        /// <param name="subject">
        /// The subject line of the e-mail message.</param>
        /// <param name="noteText">
        /// The text of the e-mail message.</param>
        /// <param name="recipients">
        /// An <see cref="Array"/> of <see cref="MapiAddress"/> instances holding the display names
        /// and SMTP addresses of all message recipients. The protocol identifier "smtp:" is
        /// automatically prepended to any non-empty addresses without this prefix.</param>
        /// <param name="attachments">
        /// An <see cref="Array"/> of <see cref="MapiAddress"/> instances holding the display names
        /// and fully qualified local file paths of any attachment files sent to the <paramref
        /// name="recipients"/>.</param>
        /// <exception cref="MapiException">
        /// <see cref="Mapi.MAPISendMail"/> indicated an error.</exception>
        /// <remarks><para>
        /// <b>SendMail</b> creates and sends an e-mail message with optional file attachments,
        /// using the Win32 API call <see cref="Mapi.MAPISendMail"/> which is part of the Simple
        /// MAPI protocol. The originator is left undefined which will cause Simple MAPI to assert
        /// the user’s default e-mail account as the originator.
        /// </para><para>
        /// The <paramref name="subject"/> and <paramref name="noteText"/> parameters may be a null
        /// reference or an empty string to leave the corresponding field blank. The <paramref
        /// name="recipients"/> and <paramref name="attachments"/> parameters may be null references
        /// or empty arrays to create a message without recipients or file attachments,
        /// respectively.
        /// </para><para>
        /// The e-mail message is presented to the user who can choose to edit (filling in any blank
        /// fields or adding text as desired), send, or cancel the message. User cancellation
        /// generates a <see cref="MapiException"/> whose <see cref="MapiException.Code"/> is <see
        /// cref="MapiException.Abort"/>.</para></remarks>

        public static void SendMail(string subject, string noteText,
                                    MapiAddress[] recipients, MapiAddress[] attachments)
        {
            // remember current working directory
            string currentDir = Directory.GetCurrentDirectory();

            // construct MAPI message descriptor
            MapiMessage message = new MapiMessage();

            message.lpszSubject  = subject;
            message.lpszNoteText = noteText;

            try {
                // create any specified recipients
                if (recipients != null && recipients.Length > 0)
                {
                    // store count of recipient descriptors
                    int count = recipients.Length;
                    message.nRecipCount = (uint)count;

                    // allocate memory for recipient descriptors
                    int size = Marshal.SizeOf(typeof(MapiRecipDesc));
                    message.lpRecips.AllocateHandle(count * size);

                    // construct recipient descriptors
                    MapiRecipDesc recip = new MapiRecipDesc();
                    for (int i = 0; i < count; i++)
                    {
                        // prepend "smtp:" to address if not present
                        string address = recipients[i].Address;
                        if (!String.IsNullOrEmpty(address) &&
                            !address.StartsWith("smtp:", StringComparison.OrdinalIgnoreCase))
                        {
                            address = "smtp:" + address;
                        }

                        // create MAPI recipient descriptor
                        recip.ulRecipClass = MapiRecipClass.MAPI_TO;
                        recip.lpszName     = recipients[i].Name;
                        recip.lpszAddress  = address;

                        // copy recipient descriptor to unmanaged memory
                        message.lpRecips.SetMemory(recip, i * size, false);
                    }
                }

                // create any specified attachments
                if (attachments != null && attachments.Length > 0)
                {
                    // store count of attachment descriptors
                    int count = attachments.Length;
                    message.nFileCount = (uint)count;

                    // allocate memory for attachment descriptors
                    int size = Marshal.SizeOf(typeof(MapiFileDesc));
                    message.lpFiles.AllocateHandle(count * size);

                    // construct attachment descriptors
                    MapiFileDesc fileDesc = new MapiFileDesc();
                    for (int i = 0; i < count; i++)
                    {
                        // create MAPI file attachment descriptor
                        fileDesc.lpszFileName = attachments[i].Name;
                        fileDesc.lpszPathName = attachments[i].Address;
                        fileDesc.nPosition    = 0xffffffff; // don’t embed files

                        // copy attachment descriptor to unmanaged memory
                        message.lpFiles.SetMemory(fileDesc, i * size, false);
                    }
                }

                // invoke MAPISendMail to deliver this message
                MapiFlags flags = MapiFlags.MAPI_DIALOG | MapiFlags.MAPI_LOGON_UI;
                MapiError code  = Mapi.MAPISendMail(UIntPtr.Zero, UIntPtr.Zero, message, flags, 0);

                // throw exception if MAPI reports failure
                if (code != MapiError.SUCCESS_SUCCESS)
                {
                    ThrowMapiException(code);
                }
            }
            finally {
                // release unmanaged memory blocks
                message.Dispose();

                // restore original working directory
                Directory.SetCurrentDirectory(currentDir);
            }
        }
        public static void Run()
        {
            // ExStart:RemovePropertiesFromMSGAndAttachments
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_Outlook();

            MapiMessage mapi = new MapiMessage("*****@*****.**", "*****@*****.**", "subject", "body");
            mapi.SetBodyContent("<html><body><h1>This is the body content</h1></body></html>", BodyContentType.Html);
            MapiMessage attachment = MapiMessage.FromFile(dataDir + @"message.msg");
            mapi.Attachments.Add("Outlook2 Test subject.msg", attachment);
            Console.WriteLine("Before removal = " + mapi.Attachments[mapi.Attachments.Count - 1].Properties.Count);

            mapi.Attachments[mapi.Attachments.Count - 1].RemoveProperty(923467779);// Delete anyone property
            Console.WriteLine("After removal = " + mapi.Attachments[mapi.Attachments.Count - 1].Properties.Count);
            mapi.Save(@"EMAIL_589265.msg");

            MapiMessage mapi2 = MapiMessage.FromFile(@"EMAIL_589265.msg");
            Console.WriteLine("Reloaded = " + mapi2.Attachments[mapi2.Attachments.Count - 1].Properties.Count);
            // ExEnd:RemovePropertiesFromMSGAndAttachments
        }