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

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.

Related

Save OLE Embedded documents in Outlook email to file

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.

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.

MailCore2 - Fetch message content without downloading images or attachments?

I want to provide a preview of a user's messages, but I don't wish to download attachments just in order to do that.
The information I need is:
Subject
Date
Sender information (display name if available, email address)
Plain-text message
By calling the method fetchMessagesByNumberOperationWithFolder: with request kind MCOIMAPMessagesRequestKindHeaders, I get the date and subject, but it's very slow to return if any of the messages have attachments. By calling it with request kind MCOIMAPMessagesRequestKindUid, it returns very quickly, with just the Uid (and the current date, as a placeholder). From there, I still need to get the subject, the date and the sender.
Now I'm still trying to get this information, while avoiding downloading message attachments.
Calling fetchParsedMessageOperationWithFolder: or fetchMessageOperationWithFolder: both download the message with attachments, and are thus very slow to return.
Because fetchMessageOperationWithFolder: completes with a NSData object, checking the size of the given object reveals it to be the size of a regular message, plus its' attachment.
What can I do to get the information I need, without downloading any attachments?
EDIT: Calling requiredPartsForRendering could give me the content of the email, but in order to retrieve the Date and sender information, I'd still have to have a request kind of MCOIMAPMessagesRequestKindHeaders, which would download the attachment.
So to clarify:
I want to get the following information from an IMAP email, without downloading the email attachments:
Subject
Date
Sender information (display name if available, email address)
Plain-text message
The following methods should be helpful to you:
-[MCOAbstractMessage requiredPartsForRendering] will return the message parts that you needs to fetch to be able to show the text content of the message.
-[MCOIMAPSession fetchMessageAttachmentOperationWithFolder:uid:partID:encoding:] will help you fetch each of those parts.
-[MCOIMAPMessage htmlRenderingWithFolder:delegate:] will return the rendered content as HTML (or nil if you don't provide all the content of the parts through the delegate.
-[NSString mco_flattenHTML] is also useful if you'd like to convert the HTML to a unformatted string.

Adding custom attributes to Task?

How can i add custom attributes/data to Task via API . for example we wanted to add field like customer contact number or deal amount e.t.c
We don't currently support adding arbitrary metadata to tasks, though it's something we're thinking about. In the meantime, what many customers do is to simply put data in the note field in an easily-parseable form, which works well and also lets humans reading the task see the e.g. ticket number.
It's not a terribly elegant solution, but it works.
https://asana.com/developers/documentation/getting-started/custom-external_data
Custom external data allows a client application to add app-specific metadata to Tasks in the API. The custom data includes a string id that can be used to retrieve objects and a data blob that can store character strings.
See the external field at https://asana.com/developers/api-reference/tasks

Copying a list of subscribed data in System center orchestrator

I'm using System Center Orchestrator 2012, and I have a generic error handler which is connected to all the activities in my runbook.
I have subscribed to a list of published data as a parameter in this error handler, which looks like this:
Activity Name : {Activity Name from "Monitor File"}{Activity Name from "Move file"}.......
What I need to do is copy this list of subscribed data and do a search and replace to change the Activity Name parameter to something else, say Error Message. Whenever I copy this list of variables, I get gibberish when I paste it
\`d.T.~Ed/{598EBDFA-BF5B-4B77-8156-E6FA6ECD0CE1}.Object.Name\`d.T.~Ed/\`d.T.~Ed/{6838D741-DF8E-4C25-8C28-D06A52F67D36}.Object.Name\`d.T.~Ed/\`d.T.~Ed/{D1D9BBE6-5AAF-4D8F-A98A-1A8BDD977E7E}.Object.Name\`d.T.~Ed/\`d.T.~Ed/{9EC92323-1B9B-4D06-88E9-A97BA525CF5A}.Object.Name\`d.T.~Ed/\`d.T.~Ed/{FAD32B4C-92CC-40BD-837A-4C5F22C2E018}.Object.Name\`d.T.~Ed/\`d.T.~Ed/{DFF7A110-ACFD-4377-AFEC-16B5BEC8BFF4}.Object.Name\`d.T.~Ed/\`d.T.~Ed/{139ACC4E-CF6D-4EEE-BD88-9DC1E0FC2038}.Object.Name\`d.T.~Ed/\`d.T.~Ed/{1484789C-BB37-4507-AD21-E367665E0BE6}.Object.Name\`d.T.~Ed/\`d.T.~Ed/{01EA8BD0-69C5-4959-86DB-29FAD34D144A}.Object.Name\`d.T.~Ed/\`d.T.~Ed/{A60C582B-5DD0-41F7-BB0A-B5D71C3B9ECB}.Object.Name\`d.T.~Ed/\`d.T.~Ed/{1FA1E2D6-813D-4A4A-A5CD-07EB2AD4AC9B}.Object.Name\`d.T.~Ed/
Is there a way to simply copy the text? If not, I will have to click on all the activities over and over again to subscribe to different types of data.
Thanks in advance
The gibberish you're seeing is how Orchestrator translates the published data and variables to the database guids. Copying this out will always translate to the DB guids, so there's no way to do a copy/replace with "activity name" for "Error Summary". You'd need to subscribe to each activity's data or look up all of the guids which probably wouldn't be easier.
Unfortunately, setting up the error handling process in SCOrch becomes tedious to be effective.
I use a separate email linked to each activity to give more information based on the error message. I don't like to use generic error emails with published data from multiple activities since it doesn't necessarily give all the useful information you need (or an end user will be able to understand).

Resources