Welcome To The Home Of The Visual FoxPro Experts  
home. signup. forum. archives. search. google. articles. downloads. faq. members. weblogs. file info. rss. print.
OUTLOOK AUTOMATION PART 3

So let’s start with the very basic sending an e-mail, the code for this is:

 
LOCAL loOutlook   AS Outlook.Application
LOCAL loNameSpace AS Outlook.NameSpace 
LOCAL loMailItem  AS Outlook.MailItem
LOCAL llShowItem  AS Boolean
 
#DEFINE olMailItem   0
 
loOutlook   = CREATEOBJECT('Outlook.Application')
loNameSpace = loOutlook.GetNamespace("MAPI")
loNameSpace.Logon
loMailItem  = loOutlook.CreateItem( olMailItem )   && This creates the MailItem Object
llShowItem  = .T.
 
WITH loMailItem
    .Subject = "Test Email with VFP Automation"
    .Recipients.Add("fred.bloggs@bloggsville.com")
    .Body    = "This is the Main Text of the email" 
 
    IF llShowItem
       .Display      && Shows the New Message Dialog with all details from 
                      && above filled in.  
    ELSE
       .Send         && Calling this will cause a Security Dialog
    ENDIF
ENDWITH

I will show how to use Redemption at this point, I will cover this in more depth later on, but I will show it now so that you can see how it bypasses the Security.


LOCAL loOutlook   AS Outlook.Application
LOCAL loNameSpace AS Outlook.NameSpace 
LOCAL loMailItem  AS Outlook.MailItem
LOCAL loSafeItem  AS Object 

#DEFINE olMailItem   0

loOutlook   = CREATEOBJECT('Outlook.Application')
loNameSpace = loOutlook.GetNamespace("MAPI")
loNameSpace.Logon
loMailItem  = loOutlook.CreateItem( olMailItem )   && This creates the MailItem Object
loSafeItem  = CREATEOBJECT(‘Redemption.SafeMailItem’)

WITH loSafeItem
    .Item    = loMailItem     && This attaches the Mail Object to 
                              && Redemption SafeMailItem Object
    .Recipients.Add("fred.bloggs@bloggsville.com")
    .Subject = "Test Email with VFP & Redemption"
    .Body    = "This is the Main Body of the Message"
    .Send   && this does not cause the Security Dialog to be displayed.
ENDWITH 

Another way to add recipients to the Message is to use the ‘To’ Property but this is not the Recommended way, it is better to use the ‘Recipients.Add’ method.

This next table shows the Properties you will most likely use:

PropertyTypeDescriptionSubjectCharacterThis is the Subject of the Message, you also can use thisas an index into the Items CollectionBodyCharacterThis is the Main Text of the MessageRecipientsObjectThis is the Recipient Collection Object, you need to callthis for every person you wish to send the mail toToCharacterThis is a Semi colon separated list of recipients youwish to send the mail to, recommended way is to use the Recipients ObjectCCCharacterThis is also a Semi colon separated list of people receivingcopies, likewise it is recommended way is again to use the Recipients ObjectBCCCharacterThis is also a Semi colon separated list of people receivingblind copies, likewise it is recommended way is again to use the Recipients ObjectImportanceNumericThe Priority of the message, this corresponds to the Importancefield in the Options dialog.olImportanceLow0olmportanceNormal1 (Default)olImportanceHigh2SensitivityNumericThe Privacy level of the Message, this corresponds tothe Sensitivity field in the Options dialog.olNormal0olPersonal1olPrivate2olConfidential3AttachmentsObjectThis is Collection used to Add attachments to the messageobject.

Right so let’s look at the other properties of the MailItem.

Property: AlternateRecipientAllowed
This is a Read/Write Property and is a Boolean value, will be True if the mail message can be forwarded.

Property: AutoForwarded
This is a Read/Write Property and is a Boolean value, will be True if the mail message was automatically forwarded.

Property: AutoResolvedWinner - New in Outlook 2003
This is a Read only Property and is a Boolean value, True determines if the item is a winner of an automatic conflict resolution. A value of False does not indicate that the item is a loser of an automatic conflict resolution; the item should be in conflict with another item. Example:

*-- This example requires you have Outlook already open
*-- and one of the Mail items is selected.
LOCAL loOutlook  AS Outlook.Application
LOCAL loMailItem AS Outlook.MailItem
 
loOutlook = CREATEOBJECT('Outlook.Application')
loMailItem = loOutlook.ActiveInspector.CurrentItem 

IF loMailItem.Conflicts.Count > 0 
    IF loMailItem.AutoResolvedWinner 
       MESSAGEBOX("This Item is a winner in an automatic conflict resolution")
    ELSE
       MESSAGEBOX("This item is a loser in an automatic conflict resolution.")
    ENDIF 
ELSE
    MESSAGEBOX("This item is not in conflict with any item.")
ENDIF 

Property: BillingInformation
This is a Read/Write Property and is free-form text, Returns or sets the value representing the billing information associated with the item.

Property: BodyFormat
This is a Read/Write Property and is numeric, Returns or sets the Body format of the Body text, Outlook provides three text options and these are: Plain Text, Rich Text and HTML. Example:

 
LOCAL loOutlook  AS Outlook.Application
LOCAL loMailItem AS Outlook.MailItem

#DEFINE olMailItem   0
#DEFINE olFormatHTML 2

loOutlook  = CREATEOBJECT(‘Outlook.Application’)
loMailItem = loOutlook.CreateItem( olMailItem )
WITH loMailItem
    && Set body format to HTML
    .BodyFormat = olFormatHTML
    .HTMLBody   = "The body of this message will appear in HTML." + ;
                  "Type the Message text here."
    .Display
ENDWITH

The other type constants are:

ConstantValueolFormatUnspecified0olFormatPlain1olFormatHTML2olFormatRichText3

All text formatting will be lost when the BodyFormat property is switched from RTF to HTML and vice-versa. In earlier versions of Outlook, the BodyFormat property returned the olFormatUnspecified constant for a newly created item that has not been displayed or whose BodyFormat property is not yet set programmatically. In Microsoft Office Outlook 2003, the property returns the format that is currently set in the Outlook user interface.

Property: Categories
This is a Read/Write property and is of string value; you can return or set the string representing the category assigned to the form description. Example:

LOCAL loOutlook  AS Outlook.Application
LOCAL loMailItem AS Outlook.MailItem

#DEFINE olMailItem   0

loOutlook  = CREATEOBJECT(‘Outlook.Application’)
loMailItem = loOutlook.CreateItem( olMailItem )
WITH loMailItem
    .Subject    = "Test for Categories dialog"
    .Categories = "Ideas"
    .Display
    .ShowCategoriesDialog
ENDWITH

Property: Companies
This is a Read/Write property and is of string value; you can return or set the string representing the names of companies associated with the item.

Property: ConversationIndex
This is a Read only property and is of string value; the value returned represents the index of the conversation thread of the item.

Property: ConversationTopic
This is a Read only property and is of string value; the value returned represents the topic of the conversation thread of the item.

Property: CreationTime
This is a Read only property and is of DateTime value; the value returned is the Date and Time that the item was created.

Property: DeferredDeliveryTime
This is a Read/Write property and is of DateTime value; you can return or set the date & time for when the Message is to be delivered. Example:

LOCAL loOutlook  AS Outlook.Application
LOCAL loMailItem AS Outlook.MailItem

#DEFINE olMailItem   0

loOutlook  = CREATEOBJECT(‘Outlook.Application’)
loMailItem = loOutlook.CreateItem( olMailItem )

WITH loMailItem
    .Subject    = "Test for deferred delivery time"
    .DeferredDeliveryTime = "10/10/2005 17:00"
    .Display
ENDWITH

To check this has been set select the View/Options from the menu of the mail item, and check the Do Not Delivery before option.


Property: DeleteAfterSubmit
This is a Read/Write property and is of Boolean value; if this value is True then a copy of the message is not saved when it has been sent, if False then a copy of the message will be saved.

Property: DownloadState
This is a Read only property and is a numeric value; the value of this property represents the download state of the item.

ConstantValueolFullItem1olHeaderOnly0

Example:

LOCAL loOutlook AS Outlook.Application 
LOCAL loInBox   AS Outlook.MAPIFolder 
LOCAL loItems   AS Outlook.Items
LOCAL loObj     AS Outlook.MailItem 
LOCAL lnI       AS Integer, liCount AS Integer 

#DEFINE olFolderInbox             6
#DEFINE olHeaderOnly       0 
#DEFINE olMarkedForDownload 2

loOutlook = CREATEOBJECT('Outlook.Application')
loInBox   = loOutlook.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
loItems   = loInbox.Items 
liCount   = loItems.Count 
 
FOR lnI = 1 TO liCount 
    loObj = loItems.Item[lnI]
    *-- Verify if the state of the item is olHeaderOnly
    IF loObj.DownloadState = olHeaderOnly 
       MESSAGEBOX("This item has not been fully downloaded.")
       *-- Mark the item to be downloaded.
       loObj.MarkForDownload = olMarkedForDownload 
       loObj.Save 
    ENDIF
ENDFOR

Property: EnableSharedAttachments - New in Outlook 2003
This is a Read/Write property and is of Boolean value; the value of this property determines whether the Attachment Options task pane will be displayed in the Outlook user interface for an e-mail item.

Property: EntryID
This is a Read only property of string value, the value returned is the unique entry ID of the object. A MAPI store provider assigns a unique ID string when an item is created in its store. Therefore, the EntryID property is not set for a Microsoft Outlook item until it is saved or sent. The EntryID changes when an item is moved into another store, for example, from your Inbox to a Microsoft Exchange Server public folder or from one Personal Folders (.pst) file to another .pst file. Solutions should not depend on the EntryID property to be unique unless items will not be moved. The EntryID property returns a MAPI long-term EntryID. For more information about long- and short-term EntryIDs, search http://msdn.microsoft.com for PR_ENTRYID.

Property: ExpiryTime
This is a Read/Write property of DateTime value, this value indicates at which date and time the item becomes invalid and can be deleted. Example:

LOCAL loOutlook  AS Outlook.Application 
LOCAL loMailItem AS Outlook.MailItem
 
#DEFINE olMailItem   0

loOutlook  = CREATEOBJECT('Outlook.Application')
loMailItem = loOutlook.CreateItem( olMailItem )
WITH loMailItem
    .To         = "Fred Bloggs"
    .Subject    = "Test for Expiry"
    .ExpiryTime = "10/08/2005 17:00"
    .Display
ENDWITH

Property: FlagDueBy
This is a Read/Write property and is of DateTime value, this value specifies a date & time by which the e-mail message is due, this property is only valid if the FlagStatus Property is also set for the message.

Property: FlagIcon - New in Outlook 2003
This is a Read/Write property and is of numeric value, Outlook 2003 has 7 flag types, these can either be returned or set, the values are:

ConstantValueConstantValueolNoFlagIcon0olYellowFlagIcon4olPurpleFlagIcon1olBlueFlagIcon5olOrangeFlagIcon2olRedFlagIcon6olGreenFlagIcon3  

Example:

LOCAL loOutlook AS Outlook.Application 
LOCAL loInBox   AS Outlook.MAPIFolder 
LOCAL loItem    AS Outlook.MailItem 
LOCAL lnI       AS Integer 
 
#DEFINE olFolderInbox      6
#DEFINE olYellowFlagIcon   4
 
loOutlook = CREATEOBJECT('Outlook.Application')
loInBox   = loOutlook.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)

*-- Find the Sender Name of Support and change the flagicon.
FOR lnI = 1 TO loInBox.Items.Count 
    loItem = loInBox.Items[lnI]
    IF loItem.SenderName = "Support"     && Security Dialog...
        loItem.FlagIcon = olYellowFlagIcon 
         loItem.Save
    ENDIF 
ENDFOR 

Property: FlagRequest
This is a Read/Write property and is of string value, this value indicates the requested action for an e-mail message, and this property is only valid if the FlagStatus property is also set for the message.

Property: FlagStatus
This is a Read/Write property and is of Numeric, this value indicates the flag status for the mail message. The constants are:

ConstantValueolFlagComplete1olFlagMarked2olNoFlag0

Property: HasCoverSheet - New in Outlook 2003
This is a Read/Write property and is of Boolean value, the value determines the setting of the Use Cover Sheet option in the Fax UI, which in turn controls what is displayed in the body of the mail item.

Property: HTMLBody
This is a Read/Write property of string type, this value should be valid HTML syntax. Setting the HTMLBody property sets the EditorType property of the Items’s Inspector to olEditorHTML. Setting the HTMLBody property will always update the Body property immediately, also note that if you set the Body property this will clear the contents of the HTMLBody property.

Property: InternetCodePage
This is a Read/Write property of Long type, this value determines the Internet Code Page used by the item, the Internet code page defines the text encoding scheme used by the item.

Property: IsConflict
This is a Read only Property of Boolean type, the value returned determines if the e-mail item is in conflict, whether or not an item is in conflict is determined by the state of the application. For example, when a user is offline and tries to access an online folder the action will fail and in this scenario the IsConflict property will return true. Example Code:

LOCAL loOutlook  AS Outlook.Application
LOCAL loMailItem AS Outlook.MailItem

loOutlook  = CREATEOBJECT('Outlook.Application')
loMailItem = loOutlook.CreateItem(0)
WITH loMailItem
    .Body = "This e-mail message was created automatically on " + ;
                       TTOC(DATETIME())
    .To   = "fbloggs@bloggsville.com"
    IF !.IsConflict
       .Send         && Security Dialog
    ELSE
       MESSAGEBOX("Conflict: Cannot send item")
    ENDIF 
ENDWITH 
loMailItem = .NULL.
loOutlook  = .NULL.

Property: IsIPFax - New in Outlook 2003
This is a Read/Write property of Boolean type, the value determines if the mail item is a fax.

Property: LastModificationTime
This is a Read only property of DateTime value; this value returns the date and time the item was last modified.

Property: MarkForDownload
This is a Read/Write property of numeric value; the value determines the status of an item once it is received by a remote user. This property gives remote users with less-than-ideal data-transfer capabilities increased messaging flexibility. Constants are:

ConstantValueDescriptionolMarkedForCopy3The item will be copied to the remote siteolMarkedForDelete4The item will be deletedolMarkedForDownload2The item will be downloaded in its entiretyolRemoteStatusNone0The item has no remote statusolUnMarked1The item isn't marked for remote status and will be disregarded

Property: MessageClass
This is a Read/Write property of string value, this value represents the message class for the Item, and this property corresponds to the MAPI property PR_MESSAGE_CLASS.

Property: Mileage
This is a Read/Write property of string value, you can return or set the string, this is a free-form string field and can be used to store mileage information associated with the item (for example, 100 miles documented for an appointment, contact, or task) for purposes of reimbursement.

Property: NoAging
This is a Read/Write property of Boolean value, if this is set to true then outlook will not age the item.

Property: OriginatorDeliveryReportRequested
This is a Read/Write property of Boolean value, you can return or set this value, the value determines whether the originator of the meeting item or mail message will receive a delivery report. Each transport provider that handles your message sends you a single delivery notification containing the names and addresses of each recipient to whom it was delivered.

Property: OutlookInternalVersion
This is a Read only property of Long value; this will return the build number of the Outlook Application.

Property: OutlookVersion
This is a Read only property of String value; this string indicates the Major and Minor version number of the Outlook Application.

Property: Permission - New in Outlook 2003
This is a Read/Write property of Numeric value, you can set this value to one of the following constants, and this determines the permissions the recipients will have on the e-mail item.

ConstantValueolUnrestricted0olDoNotForward1olPermissionTemplate2

Property: PermissionService - New in Outlook 2003
This is a Read/Write property of Numeric value, you can set this value to one of the following constants, and this determines the permission service that will be used when sending an IRM protected message. Note that this property is useful only if you have more than one permission identity for a particular SMTP address.

ConstantValueolUnknown0olWindows1olPassport2

Property: ReadReceiptRequested
This is a Read/Write property of Boolean value, if this is true then a read receipt has been requested by the sender.

Property: ReceivedByEntryID
This is a Read only Property of String value, the value returned is the EntryID for the true recipient as set by the transport provider delivering the mail message.

Property: ReceivedByName
This is a Read only property of String value, the value returned is the display name of the true recipient from the mail message.

Property: ReceivedOnBehalfOfNameEntryID
This is a Read only property of String value, the value returned is the EntryID of the user delegated to represent the recipient for the mail message.

Property: ReceivedOnBehalfOfName
This is a Read only property of String value, the value returned is the display name of the user delegated to represent the recipient for the mail message.

Property: ReceivedTime
This is a Read only property of Date Time value; the value returned is the DateTime at which the mail message was received.

Property: RecipientReassignmentProhibited
This is a Read/Write property of Boolean value; if this is true then the recipient cannot forward the mail message.

Property: ReminderOverrideDefault
This is a Read/Write property of Boolean value; if this is true then the reminder overrides the default reminder behaviour for the appointment, mail item or task. Note you must set the ReminderOverrideDefault property to validate the ReminderPlaySound and ReminderSoundFile properties.

Property: ReminderPlaySound
This is a Read/Write property of Boolean value; if this is true then reminder should play a sound when it occurs, this property must be set in order to validate the ReminderSoundFile property, also this property is only valid if the ReminderOverrideDefault property is set to true.

Property: ReminderSet
This is a Read/Write property of Boolean value; if this value is set to True then a reminder has been set for this e-mail.

Property: ReminderSoundFile
This is a Read/Write property of String value, you can Return or set the value to a path and filename of the sound file to play when the reminder occurs for the mail message. This property is only valid if the ReminderOverrideDefault and ReminderPlaySound are set to true.

Property: ReminderTime
This is a Read/Write property of DateTime value, you can return or set the value to the DateTime at which you want the reminder to appear for the specified item.

Property: RemoteStatus
This is a Read/Write Property of Numeric value, the value relates to one of the olRemoteStatus constants, these specify the remote status of the mail message, see the MarkedForDownload for Constant Table.

Property: ReplyRecipientNames
This is a Read only property of string value, the value returned will be a semicolon-delimited list of reply recipients for the mail message. The reply recipients list should be set by using the ReplyRecipients Collection.

Property: ReplyRecipients
This property will return a Recipients Collection that represents all the reply recipient objects for the mail message.

Property: Saved
This is a Read only property of Boolean Value, if this value is True then this item has not been modified since the last save.

Property: SendersEmailAddress - New in Outlook 2003
This is a Read only property of String value, the value returned is the e-mail address of the sender, Note: Microsoft Outlook blocks code that attempts to access the SenderEmailAddress property for security reasons. If you run a third-party add-in, custom solution, or other program that uses the SenderEmailAddress property in Microsoft Office Outlook 2003, you may receive the following warning:

A program is trying to access e-mail addresses you have stored in Outlook. Do you want to allow this? If this is unexpected, it may be a virus and you should choose "No".

Property: SendersEmailType - New in Outlook 2003
This is a Read only property of String value, the value returned represents the type of entry for the e-mail address of the sender of message, values are: ‘SMTP’ for internet address, ‘EX’ for a Microsoft Exchange server address, etc.

Property: SenderName
This is a Read only property of String value, the value returned is the display name of the sender of the mail message.

Property: SentOn
This is a Read only property of DateTime value, the value returned is the date and time on which the mail message was sent.

Property: SentOnBehalfOfName
This is a Read/Write property of String value, the value returned is the display name for the intended sender of the mail message.

Property: Size
This is a Read only property of Long value, the value returned is the size in bytes of the outlook item.

Property: Submitted
This is a Read only property of Boolean value, the value returned indicates if the item has been submitted, a message is always created and submitted in a folder, usually the Outbox.

Property: UnRead
This is a Read/Write property of Boolean value; if this value is true then the Item has not been read (Opened). If you recall in Part 2 of this Article I showed some code that worked through the Inbox to obtain the unread items, well since then I found a property of the actual Folder called UnReadItemCount. Example:

LOCAL loOutlook AS Outlook.Application
LOCAL loInBox   AS Outlook.MAPIFolder

loOutlook = CREATEOBJECT(‘Outlook.Application’)
loInBox   = loOutlook.GetNameSpace("MAPI").GetDefaultFolder(6) && Inbox
? loInBox.UnReadItemCount

Property: VotingOptions
This is a Read/Write property of String value, this value is a delimited string containing the voting options for the mail message.

Property: VotingResponse
This is a Read/Write property of String value, this value specifies the voting response for the mail message, and this property is usually set to one of the delimited values returned by the VotingOptions property on a reply to the original message.

So at this point we have covered the Properties, in the next part I will cover the Methods, and the Object Properties in more depth, also I will take a look at the Events. I hope you find this useful, if so then let me know, as once we have finished with the MailItem, I will revisit part 1 of the article and enhance the form so that not only will we read the folders into a tree view, but have the messages show in a list view control by the side.

ABOUT THE AUTHOR: SIMON ARNOLD

Simon Arnold Simon has worked with FoxPro for over 16 years. He currently works for a company based in Harrogate, North Yorkshire (UK), which specialises in FoxPro, Web and Unix development.
He has a weblog at http://weblogs.foxite.com/simonarnold.

FEEDBACK

harvey @ 9/17/2013 5:48:47 PM
I have a bunch of standalone MSG files that were created with drag and drop from Outlook. I want to convert them all to plain TXT files. Read some of your postings but can't find anyway to make the file load into CurrentItem. The SaveAs part is working but requires me to manually open each file of which I have several hundred to get through. Automation solution in VFP sure would be nice. Any ideas?

hm@zam.net

Simon Arnold @ 9/17/2013 6:47:02 PM
You can use the following to read properties of the MSG file

LOCAL ol as Outlook.Application
LOCAL msg as Outlook.MailItem

ol = CREATEOBJECT("Outlook.Application")
msg = ol.CreateItemFromTemplate("c:\temp\test.msg")

&& You can Access the Properties of the Msg if you like.
? msg.Subject
? msg.To

&& Save the .MSG File as Text file.
msg.SaveAs(“c:\temp\test.txt”,0) && 0 = olTXT.


msg = .null.
ol = .null.



This should help.

Herbert @ 4/6/2014 5:53:13 AM
Hi This looks like some really good stuff.

I have looked at the following:

http://social.msdn.microsoft.com/Forums/en-US/d493e88f-2362-4af7-9d5e-9a645fe43344/reading-emails-into-vfp-table?forum=visualfoxprogeneral

http://fox.wikis.com/wc.dll?Wiki~GetPopEmail~WIN_COM_API

Both look promising but both have their issues.

I am trying to get email from my web mail or my gmail into VFP so I can fiddle with it there - I have a need to store some email in vfp in a database for referencing - it's a long story.

I tried the examples from the above URLS and I tried the code below which worked fine too:

LOCAL loOutlook AS Outlook.Application
LOCAL loInBox AS Outlook.MAPIFolder

loOutlook = CREATEOBJECT(‘Outlook.Application’)
loInBox = loOutlook.GetNameSpace("MAPI").GetDefaultFolder(6) && Inbox
? loInBox.UnReadItemCount

and that worked great but
* I need to be able to tell it what folder I want it to pull emails from
* what date range I need to pull emails for ( datetime() through today-1) and not pull duplicates.

Is there any way to find some code that
* allows to pull email into vfp into a table...
* allows a user to select what folder to pull that email from
* allows a user to specify a date range to get the email from (I have about 6 years of email in Gmail and I don't want to pull all those emails)

Thanks for any help you can provide!

Herbert



Your Name: 
Your Feedback: 

Spam Protection:
Enter the code shown: