Save OLE Embedded documents in Outlook email to file - delphi

I am using late binding to connect to MS Outlook and to open and extract info from outlook emails using the MailItemobject.
I am trying to save attachments to file. This is fairly straightforward in most instances using the Attachment object and its SaveAsFile method.
However, it does not work where the Attachment Type is olOLE. I believe this only relates to documents embedded in emails created in RTF format (hopefully few and far between nowadays).
Via the Attachment object it is possible to access MAPI properties not exposed by the object model using its PropertyAccessor.
The relevant MAPI property for OLE objects is PR_ATTACH_DATA_OBJ, which can be accessed using the PropertyInspector as in the following example:
Function SaveOLEAttachmentToFile(Attachment:Variant; fn:String): boolean;
var
OPA, PropName : Variant;
begin
Result := false;
OPA := Attachment.PropertyAccessor;
PropName := 'http://schemas.microsoft.com/mapi/proptag/0x3701000D '; //PR_ATTACH_DATA_OBJ
?????? := OPA.GetProperty(PropName);
end;
I am stuck at this point as I can't know work out what Delphi type to save the data to and I am not even sure this is possible having read the MS documentation (Click here). PR_ATTACH_DATA_OBJ returns a PT_OBJECT. I am hoping that this object contains the raw data which (if I could work out how to access it in Delphi) can be simply saved to a file. However, the documentation suggests it may not be that simple and it's possible I may have to work with Extended MAPI. I have spent a few hours researching the latter with no concrete result other than a headache. I appreciate I could use Redemption, but I don't want to use a third party tool for something which is fairly minor in the round.
If anyone can advise as to a data type to hold the PT_OBJECT from which it can be simply saved to file that would be my route one.
Failing that, if I need to dig deeper into MAPI, I would be grateful if anyone could clarify/amplify my research so far. I have the following steps:
Initialize MAPI.
Get an IMAPIPROP interface. I think I should be getting the interface from my Attachment object and the following seems to work (ie compiles and executes without problems): MAPIPROP := IUnknown(Attachment.MAPIObject) as IMAPIPROP. Failing that, I would have to cast the parent MailItem to IMAPIPROP interface and work my way down to the attachment via GetAttachmentTable.
Load the attachment data into an IStream: if Succeeded(MAPIPROP.OpenProperty(PR_ATTACH_DATA_OBJ, IStream, STGM_READ, 0, IUnknown(SourceStream)) then
Extract the data from the IStream and save to file
I have failed to get as far as point 3 as something would seem to be wrong with my initial casting to IMAPIPROP albeit it does not cause any violations. I have tried reading a single property from the MailItem cast to IMAPIPROP using the following code:
if (Succeeded(HrGetOneProp(MAPIPROP, PR_SUBJECT, Prop))) then
And I get an access violation. Likewise if I cast the Attachment object and query an attachment property I also get a violation. I don't think the problem lies with the call to HrGetOneProp, I think it has to be the casting to IMAPIPROP.
Any pointers re the above would be greatly appreciated.

Not quite an answer to my question, but I have thought of an alternative solution. What I am ultimately trying to do is convert a msg email as a pdf. To do that I need to extract the body and then somehow insert the embedded images. With an html email this seemed pretty straightforward ((1) extract all the attachments to a folder, (2) parse the html body for references to SRC IMG and update the location of the image to reference the saved files and (3) save the edited html body to file and open it in Word and save as PDF).
RTF emails cannot be handled in this way. However, for my specific problem there is a much easier way to achieve what I need for all email types using Outtlook and Word.
Use the MailItem.SaveAs function and save the email in either html format or mthml. The former format will save all embedded images to a sub-folder (in png and jpg formats) should you need them for any other reason. once you have your html file, open it with Word and save to PDF.
If Office is not a solution then you need to figure Istorage or use one of the Extended MAPI solutions such as Redemption.
For Delphi users there are also the following commercial offerings that I have come across in my recent travels:
IMIBO
Scalabium
Rapware
I did come across one more solution which I can't find at the moment! Will post an update if I do.

PropertyAccessor (and the Outlook Object Model in general) does not handle PT_OBJECT type properties.
What you need to do is open the PR_ATTACH_DATA_OBJ property as IStorage, and then extract the data from there (it depends on the actual type of the attachment). You can see the data in the streams in OutlookSpy (I am its author) - select the message, click IMessage button on the OutlookSpy rubbon, go to the GetAttachmentTable tab, double click on the attachment to open it, select the PR_ATTACH_DATA_OBJ property, right click, select IMAPIProp::OpenProperty, then IStorage.
If using Redemption (I am also its author) is an option, its version of RDOAttachment.SaveAsFile handles OLE attachment for the most popular formats (Word, Excel, bitmap, Power Point, Adobe PDF, etc.) - create an instance of the RDOSession object (using either CrealeOleObject or RedemptionLoader) and use RDOSession.GetRDOObjectFromOutlookObject method (pass either Attachment or MailItem object) to get back RDOMail or RDOAttachment object respectively.

Related

TDBrichedit displays plain text rather than rich text

The context is that I am maintaining an application running on delphi 7 with the BDE. I programmatically assign dbricheditcontrols' datafields to allow users to edit rtf documents. When the relevant forms open, the unformatted text is displayed and then once say the person moves onto the next document, suddenly the rich text kicks in; I suspect it must be an initialisation problem of sorts, but what am I missing; could not locate a solution online.
Thanks
Ordinarily, I would not post an answer to a q which states
I programmatically assign dbricheditcontrols' datafields to allow users to edit rtf documents
but fails to include the code that you are using - you should have provided an MCVE (see https://stackoverflow.com/help/mcve).
However, what you say sugggests that you may be going about what you are trying to do the wrong way. You say you are using a TDBRichEdit component, but if you are using it correctly, it should not require any programmatic assignment of datafields to do it: you simply need to connect the component to the TTable or TQuery you are using via a TDataSource component, and configure the DBRichEdit to access whatever field of the TTable/TQuery that stores the richedit text. That can be done a design time using the Object Inspector in the IDE to set properties and does not require any code.
So, it seems to me that either you are not using the DBRichEdit correctly, or you are trying to do something that you have not explained in your q.
You can satisfy yourself that a DBRichEdit works automatically, without needing to load or save its contents in code, as follows:
Open the FishFacts demo
Add a TDBNavigator and a TDBRichEdit to the form. Set the DataField property of DBRichEdit1 to Notes.
Set the ReadOnly property of Table1 to False. Then set Table1's Active property to True.
Compile and run the project. While it's running
Start WordPad.Exe and create a bit of richtext in it. Copy it to the clipboard. Click the Save speedbutton of DBNavigator1.
Paste the richtext into DBRichEdit1.
You should find that you can navigate away from and back to the edited record and the richtext will be automatically reloaded.
Also, the following code works fine for me to load the Notes field from an .Rtf file
procedure TForm1.Button1Click(Sender: TObject);
begin
Table1.Edit;
TMemoField(Table1.FieldByName('Notes')).LoadFromFile('D:\test.rtf');
end;
and does not initially display the unformatted text as you describe. So I'm fairly sure you problem is arising in code of yours that you haven't shown us.
Btw, the only reason I am posting this as an "answer" is that there is more to say than will comfortably fit in a comment.

Delphi and attachment files in MS access database

I search many times in Google, SO, and I can't find anything about working with attachment via delphi, so I decide to write this question.
I have a table in .accdb database called Files with those fields:
IDFile PK AutoIncField,
FileName WideStringField,
FilesAttached WideMemoFiled.
How can I save/load files to/from attachment fields using delphi?
Attach files and graphics to the records in your database
The problem here, in delphi the datatype of FilesAttached is TWideMemoField,
when I write ShowMessage(FDTable1FilesAttached.Value); it give just the name of the attachment.
I don't know how to Insert/save files to/from that field using delphi.
It didn't seem that hard to find VBA/C# examples of working with .accdb Attachment fields which should translate fairly easily into Delphi. However, it turned out to be more difficult than I imagined to find something that a) hadn't misunderstood what Attachment fields actually are and b) actually works. Skip to the update section below.
For example, googling
accdb create attachment in vba
gives numerous hits including this one
http://sourcedaddy.com/ms-access/working-with-attachment-fields.html
which you might try as a starting point. It uses MS DAO objects, and includes straightforward code for storing files to Attachment fields and for accessing them. You would need to create a Delphi wrapper unit for the DAO type library, if you don't already have one, using the IDE's Import Type Library
If you would prefer something ADO-based, you might take a look at
https://www.codeproject.com/Questions/843001/Handling-fields-of-Attachment-type-in-MS-Access-us
Update See the function OpenFirstAttachmentAsTempFile in the post by "aspen" (date = 4/11/2012 07:18 am) in this thread
https://access-programmers.co.uk/forums/showthread.php?t=224112&page=2
which shows an apparently successful attempt to extract a file from an attachment field (the thread also contains several other attempts at coding this function).
Note in particular this line
Set rstChild = rstCurrent.Fields(strFieldName).Value ' the .Value for a complex field returns the underlying recordset
which implies that the Value of the attachment field can return a recordset which contains the attached file(s).
Presumably, importing a recent version of the DAO type library into Delphi would allow
a Delphi app to do the same thing, and then one could reverse-engineer the rstChild recordset to see how to populate this field in code. I haven't done that yet, though.

Download email attachment files using Indy IMAP4 in C++ Builder

I am looking for a step by step solution on how to download mail attachments using Indy Imap in C++ Builder (I use C++ Builder XE8). I have read some tutorial in Delphi, but really getting Confused.
For example, what should I do after selecting the mailbox?
ImapClient->UIDRetrieve()
or
ImapClient->RetrieveStructure()
or
ImapClient->RetrievePart()
or
ImapClient->RetrieveEnvelop().
Then, what should I do next to identify the MessagePart no, haveing the attachment file?
The Last One, how to save that file to local drive?
Should I translate the following in C++?
TIdAttachmentFile(mbMsgP.MessageParts.Items[liCount]).SaveToFile(fName);
But I cant create a statement like this
TIdAttachmentFile(IdMessage1->MessageParts->items[no])->SaveToFile("filename");
I have read some tutorial in Delphi, but really getting Confused.
Not surprising, since IMAP is a complex and confusing protocol in general. That is why TIdIMAP4 has so many more methods compared to other mailbox protocols like TIdPOP3 and TIdSMTP (and it doesn't even implement everything IMAP is capable of).
For example, what should I do after selecting the mailbox?
ImapClient->UIDRetrieve() or ImapClient->RetrieveStructure() or ImapClient->RetrievePart() od ImapClient->RetrieveEnvelop().
That really depends on what you intend to do with the emails and their attachments.
(UID)Retrieve() downloads an entire email, parsing it into a TIdMessage and marking it as "read" on the server.
(UID)RetrieveStructure() retrieves the parent/child hierarchy of the various MiME parts within an email, creating an entry for each part in a TIdMessage.MessageParts or TIdImapMessageParts collection, providing some basic descriptive information about each part such as content type and part number. The actual content of each part is not retrieved.
(UID)RetrievePart() retrieves the actual content of a specific MIME part of an email. You do not need to download the entire email. But you do have to download the email's structure first so that you know the part number that you want to retrieve.
(UID)RetrieveEnvelope() retrieves some basic top-level headers for an email: date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to, and message-id.
Then, what should I do next to identify the MessagePart no, haveing the attachment file?
If you download an entire email, you would have to loop through its MessageParts collection looking for a TIdAttachment object containing the desired filename/contenttype that you are interested in.
If you download just a part of an email, you would have to retrieve the email's structure and loop through the resulting collection looking for an entry containing the desired filename/contenttype that you are interested in, then you can request that specific part's content.
The Last One, how to save that file to local drive?
If you download an entire email, then you would call SaveToFile() on the desired TIdAttachment object:
static_cast<TIdAttachment*>(IdMessage1->MessageParts->Items[no])->SaveToFile("filename");
If you download an email's structure, you can use (UID)RetrievePart() to retrieve the attachment's data into a TStream object, such as a TFileStream.

ASP.net MVC Export To Excel

I am currently exporting to Excel using the old HTML trick, where I set the MIME type to application/ms-excel. This gives the added benefit of nicely formatted tables, however the negative of the excel document not being native Excel format.
I could export it as CSV, but then this would not be formatted.
I have read brief snippets that you can export it as XML to create the Excel document, but cannot find too much information on this. Does anybody know of any tutorials and/or benefits of this? Can it be formatted tables using this method?
Thanks.
Easiest way, you could parse your table and export it in Excel XML format, see this for example: http://blogs.msdn.com/b/brian_jones/archive/2005/06/27/433152.aspx
It allows you to format the table as you whish (borders, fonts,colors, I think even formulas), and Excel will recognize it as native excel format. As a plus, you can use other programs that can import Excel XML (ie.Open office, Excel viewer,etc) and you do not need to have Office components installed on the server.
Check out ExcelXmlWriter.
We've been using it for some time and it works well. There are some downsides to the xml format however. Since it's unlikely your end users will have the .xml extension associated with Excel, you end up having to download files as .xls with an Excel mime type. When a user opens a file downloaded in this way they get a warning that the file is not in xls format. If they click through it, the file opens normally.
The only alternative is a paid library to generate native Excel files. That's certainly the best solution but last time we looked there were no good, free libraries (may have changed)
Bill Sternberger has blogged a very simple solution here:
export to excel or csv from asp.net mvc
Just today I had to write a routine that exported data to excel in an MVC application. Here's the details so someone may benefit in the future, first the user had to select some date ranges and areas for the report. On the post back, this method was in place, with TheModelTypeList containing the data from LINQ/Entity Framework/SQL Query returning strong types:
if (ExportToExcel) {
var stream = new MemoryStream();
var serializer = new XmlSerializer(typeof(List<SomeModelType>));
serializer.Serialize(stream, TheModelTypeList);
stream.Position = 0;
FSR = new FileStreamResult(stream, "application/vnd.ms-excel");
}
The only catch on this one was the file type was not known when opening so the system prompted for the application to open it... this is a result of the content being XML.... I'm still working on that.
I am using Spreadsheet Light, an Open-Source library that provides ridiculously easy creation, manipulation and saving of an Excel sheet from C#. You can have an MVC / WebAPI Controller do the work of creating the file and either
Return a URL link to the saved Excel file to the page and invoke Excel to open it with an ActiveX object
Return a Data Content Stream to the page
Return a URL link to the calling page to force an Open / Save As dialog
http://spreadsheetlight.com/

How to store a picture within Active Directory using Ruby in a Rail3App?

All I want to do is to upload an image into the Active Directory. So far I can update any AD information but the image. I have tried to search for some idea but came up with nothing so far.
Do I have to encode an image in a certain way? Do I just ldap-replace the jpegPhoto attribute with a byte-string of the photo?
Any hint towards a solution would be great.
Thanks in advance!
First of all, there is an attribute in Active directory called thumbnailPhoto. According to this Microsoft article The thumbNailPhoto attribute contains octet string type data. The AD interprets octet string data as an array of bytes.
If you want a sample code in C# you can get something here.
On the theorical point of view you can also inject a photo with LDIF using tools like "B64" to code your image file in base 64.
Secondly, On my point of view a Directory is not a database.
So, even if the attribute exists (created by netscape according to the OID 2.16.840.1.113730.3.1.35), even if Microsoft explain us how to put a picture into Active Directory, I think that it's better to register an URL, or a path to a file from a file system into a Directory.
I have no idea of the impact on performance of AD if I load each entry with 40 Ko (average size of a thumbnail photo). But I know that if there are bad written programs on the network, I mean kind of program that load all the attributes when they search an entry into the directory, this will considerably load the network.
I hope it helps.
JP
I had this issue and was able to get it working by creating a File stream and passing it through to #ldap.replace_attribute as a binary file. i.e.
thumbnail_stream = open("path_to_file")
#ldap.replace_attribute USERS_DN, :thumbnailPhoto, File.binread(thumbnail_stream)
Where #ldap is an instance of net/ldap, bound to AD. i.e.
#ldap = Net::LDAP.new
#ldap.host = ''
#ldap.port = ''
#ldap.auth USERNAME, PASSWORD
#ldap.bind

Resources