360Works Email/Documentation

From 360Works Product Documentation Wiki
Jump to: navigation, search

Contents

360Works Email User Guide

Every program attempts to expand until it can read mail. Those programs which cannot so expand are replaced by ones which can.
-Jamie Zawinski's Law of Software Envelopment


The 360Works Email Plugin offers the following advantages over FileMaker's built-in mail functionality:

  • Read messages from a mailbox (POP, IMAP)
  • Works with Instant Web Publishing / Schedules Server Scripts
  • Send multiple attachments in a single message
  • Send formatted (HTML, etc) emails
  • Speedy delivery of many messages by re-using a single connection to the server
  • Set custom email headers

Example Usages

EmailQuickSend, the easiest way to fire off a single email:

Set Variable [ $result =
    EmailRegister( "mylicensekey", "My Company" ) and
    EmailConnectSMTP( "mail.example.com" ) and
    EmailQuickSend(
        Email::from ;    // required "from" address
        Email::to ;      // comma-separated list of addresses
        Email::subject ; // subject of the message
        Email::body ;    // message body
        Email::attach    // path or URL or container to attach
    ) and
    EmailDisconnect
]


Sending a plain-text email with one attachment:

Set Variable [ $result =
    EmailRegister("myLicenseKey"; "My Company") and
    EmailConnectSMTP( "mail.example.com" ) and
    EmailCreate( Email::from ; Email::to ; Email::subject ) and
    EmailSetBody( Email::body ; "plain" ) and
    EmailAttachFile( $attachment ) and
    EmailSend and
    EmailDisconnect
]


Sending an HTML-formatted email (converts formatted FileMaker text to HTML using the GetAsCSS function):

Set Variable [ $result =
    EmailRegister("myLicenseKey"; "My Company") and
    EmailConnectSMTP( "mail.example.com" ) and
    EmailCreate( Email::from ; Email::to ; Email::subject ) and
    EmailSetBody( GetAsCSS( Email::body ); "html" ) and
    EmailSend and
    EmailDisconnect
]


Sending a single message multiple times to different recipients can be done by creating a message using EmailCreate, then calling EmailRecipients and EmailSend multiple times. If you are sending large messages with attachments, this avoids the overhead of creating a separate message for each recipient.

You can also send a single message to multiple TO, CC, or BCC recipients by passing a comma-separated list of addresses.

Note: Email is sent from whichever machine the plugin is being used on, be sure to open up port 25 for outgoing SMTP access on those machines.

Displaying a name instead of the FROM address

The "from" field can be either an email address "you@yourdomain.com" or a name and email address like "FirstName LastName <you@yourdomain.com>" instead. Most email clients will then display the name in the from field instead of the address. However, if the address is already in address book, most clients are configured to preempt with that associated name instead.

Sending Attachments

The EmailAttachFile accepts several different types of arguments. You can pass in a container field URL, or a path. A URL can be to a resource on the web, or can be a file url pointing to a local file (e.g. file:///path/to/attachment.jpg).

Bulk Mail

When sending to multiple recipients, instead of creating a new message for each recipient, you can create a single message, connect once to your server, and then send the same message multiple times, switching the subject, recipients, and message body for each recipient.

// First connect to the SMTP server and create the message.
Set Variable [ $msgCreate =
    EmailConnectSMTP( "mail.example.com" ) and
    EmailCreate( Email::from ; Email::to ; Email::subject ) and
    EmailSetBody( GetAsCSS( Email::body ); "html" )
]
Go To Record/Request [ First ]
Loop
    Set Variable [ $setRecipients = EmailRecipients [ Email::to ] ]
    Set Variable [ $msgSend = EmailSend ]
    Go To Record/Request [ Next ; Exit After Last ]
End Loop
// We've sent the same message to all recipients. Now disconnect
Set Variable [ $disconnect = EmailDisconnect ]

Reading Mail

Version 1.3 of the Email Plugin introduced support for reading messages from a mailbox. The API for reading messages was revised in version 1.6.

Here is a brief example of how to read the first 25 unread messages from the server:

set variable $registerResult = EmailRegister ( license ; company )
// check for registration success here
set variable $connectResult = EmailConnectIMAP( server ; username ; password )
// check for connection success here
set variable $$importUrl = EmailReadMessages (
    "mailbox=INBOX" ;
    "viewed=false" ;
    "max=25" ;
    "attachments=true"
)
// check for import success here
If [$$importUrl = "ERROR"]
    Show Custom Dialog [EmailLastError]
    Exit Script
End If
// Import the email messages from the local XML file
// which was created by the EmailReadMessages function
Import records [$$importUrl ; Update Matching]
// Now disconnect from the IMAP server
Set Variable [ $disconnect = EmailDisconnect ]
If [$disconnect = "ERROR"]
    Show Custom Dialog [EmailLastError]
    Exit Script
End If

If you're running on FileMaker server or via IWP/CWP, you'll need to iterate over the messages, since [Import XML] is not a web-safe script step. The general pattern looks like this:

set variable $$importUrl = EmailReadMessages (
    "mailbox=INBOX" ;
    "viewed=false" ;
    "max=25" ;
    "attachments=true"
// check for import success here
Loop
    Exit Loop If [not EmailGetNextMessage]
    New Record/Request
    Set Field[ImportedMessage::date ; EmailReadMessageValue( "dateSent" )]
    Set Field[ImportedMessage::from ; EmailReadMessageValue( "from" )]
    Set Field[ImportedMessage::to ; EmailReadMessageValue( "to" )]
    Set Field[ImportedMessage::subject ; EmailReadMessageValue( "subject" )]
    Set Field[ImportedMessage::body ; EmailReadMessageValue( "body" )]
    Set Field[ImportedMessage::messageId ; EmailReadMessageValue( "messageId" )]
End Loop

Microsoft Exchange Server

To read mail from a Microsoft Exchange Server, you'll need to enable IMAP access on your exchange server. <a href="http://technet.microsoft.com/en-us/library/bb124489.aspx?ppud=4">This article</a> covers the steps for doing so. You may need to restart your server for this change to take effect. Once IMAP access is enabled, you can connect normally as described above.

Modifying Mail Messages

Version 1.6 of the Email Plugin provided the ability to modify messages on a remote mailbox. To do this, you must read the messages using the EmailReadMessages function as described above, being sure to include the flag readonly=false. Note: setting readonly=false will cause any fetched messages to be marked as "viewed"! Then iterate to a message using the EmailGetNextMessage function. Finally, use the EmailMessageSetFlag function to apply flags to a message (such as deleted, flagged, viewed, etc).

Here is an example of how to fetch any unread messages from a mailbox, marking them all as viewed (by setting readonly=false). Additionally, any messages from a certain address are marked as deleted:

Set Variable [ $result = EmailReadMessages( "viewed=false" ; "readonly=false" ) ]
If [$result = "ERROR"]
    # Handle Error Here...
End If
Loop
    Exit Loop If [not EmailGetNextMessage]
    Set Variable[$result ; EmailMessageSetFlag("viewed")
    If [EmailReadMessageValue("from") = "deleteme@example.com"]
        Set Variable[$result ; EmailMessageSetFlag("deleted")
    End If
End Loop



360Works Plugin Setup Guides

See Plugins_101 for Error reporting, installation, registration, and more.

Function Summary

  • EmailChooseFile ( { initialPath ; fileType ; title } ) — Shows a file chooser dialog where a user can browse her local hard drive.
  • EmailConnect ( host_address_deprecated { ; user_deprecated ; password_deprecated } ) — Use {@link #EmailConnectSMTP} instead.
  • EmailGetMessageCount ( { flag1 ; flag2 ; ... } ) — Returns a count of messages in a particular mailbox, INBOX is used if no mailbox is specified.
  • EmailGetNextMessage — Loads a single message which was fetched in a previous call to the EmailReadMessages function.
  • EmailInboundIsConnected
  • EmailLastError — Returns detailed information about the last error generated by this plugin.
  • EmailLicenseInfo — Retrieve information about the Email plugin licensing and version.
  • EmailListMailboxes ( { parent ; recursive } ) — Gets a return-separated list of mailboxes in a specific folder on the currently connected inbound mail server (Note: this is only useful for IMAP mailboxes, not POP).
  • EmailOutboundIsConnected
  • EmailOutgoingMessageId — Returns the Message-ID of the last message sent using the Emailer plugin.
  • EmailReadAttachment ( path { ; savePath } ) — Read a downloaded attachment into a FileMaker container field.
  • EmailReadMessages ( { flag1 ; flag2 ; ... } ) — Reads messages from the currently connected inbound mail server.
  • EmailReadMessagesFromFile ( file { ; charset=UTF-8 } ) — This reads messages from an non-directory MBOX file or raw message content file (.
  • EmailReadMessageValue ( key ) — Retrieves information about the last message which was gotten by the <code>EmailGetNextMessage function.
  • EmailVersion — Returns the version number of the Email plugin.
  • IM_GetBuddyIcon ( service ; login ; password ; buddy ) — Returns a buddy's icon.
  • IM_GetBuddyList ( service ; login ; password ) — Connects to the messaging service (if necessary) and retrieves the user's buddy list.
  • IM_GetBuddyStatusMessage ( service ; login ; password ; buddy ) — Returns a buddy's status.
  • IM_GetBuddyStatusType ( service ; login ; password ; buddy ) — Returns a buddy's status type as one of the following: "online", "idle", "away", "mobile", or "offline".
  • IsValidEmail ( email ) — Convenience function for validating an email address.

Function Detail

EmailChooseFile ( { initialPath ; fileType ; title } )

Shows a file chooser dialog where a user can browse her local hard drive. When the user selects a file or directory and clicks "OK" on the file chooser, this function returns the path to the selected file or directory. If the user hits the cancel button, nothing is returned.

File Type

By supplying a fileType parameter, you can allow the user to just select files, just select directories, or select both files and directories. The default behavior is to only allow file selection.


Note: specifying a fileType of "directories" or "files + directories" will cause a non-native file dialog to be used on some platforms, as the native dialogs may not support directory selection.

Parameters:

initialPath
optional path to set the initial dialog selection to. If empty, will default to the user's home directory.
fileType
whether to allow "files", "directories", or both "files + directories"
title
optional title string to display as the title of the FileChooser dialog

Returns: Path to the selected file, nothing if no file was selected, or "ERROR" if an error occurred.

EmailConnect ( host_address_deprecated { ; user_deprecated ; password_deprecated } )

Use EmailConnectSMTP instead. The username and password are optional, and may not be required for sending mail. This establishes a connection to the email server. When you are finished getting/sending email, you should call EmailDisconnect to close the connection.

Parameters:

host_address
the SMTP host address. This parameter may contain a port number using a colon syntax, e.g. smtp.example.com:2525
user
The optional SMTP authentication username
password
The optional SMTP authentication password

EmailGetMessageCount ( { flag1 ; flag2 ; ... } )

Returns a count of messages in a particular mailbox, INBOX is used if no mailbox is specified.

Parameters:

flags
optional flags which control how messages are counted

Returns: number of messages in the mailbox

EmailGetNextMessage

Loads a single message which was fetched in a previous call to the EmailReadMessages function.

To use this function, first call EmailReadMessages with the appropriate parameters.

Next, call EmailGetNextMessage, which returns 1 or 0 depending on whether a message was loaded.

Finally, call EmailReadMessageValue to get individual properties of the currently loaded message.

Returns: 1 if a message is loaded, 0 if there are no more messages, or ERROR if an error occurred.

EmailInboundIsConnected

EmailLastError

Returns detailed information about the last error generated by this plugin. If another plugin function returns the text "ERROR", call this function to get a user-presentable description of what went wrong.

Returns: Error text, or "" if there was no error.

EmailLicenseInfo

Retrieve information about the Email plugin licensing and version.

Returns: version, type, registeredTo values.

EmailListMailboxes ( { parent ; recursive } )

Gets a return-separated list of mailboxes in a specific folder on the currently connected inbound mail server (Note: this is only useful for IMAP mailboxes, not POP).

Parameters:

parent
optional mailbox to traverse. If not specified/empty, the root mailbox is used.
recursive
optional parameter for whether to traverse sub-folders recursively. Default is false.

Returns: a return-separated list of mailboxes. If recursion is enabled, nested mailboxes will be separated by a slash (/) character.

EmailOutboundIsConnected

EmailOutgoingMessageId

Returns the Message-ID of the last message sent using the Emailer plugin.

Returns: a Message-ID value, or "" if there was no available message.

EmailReadAttachment ( path { ; savePath } )

Read a downloaded attachment into a FileMaker container field. To download attachments, you must pass attachments=true as a parameter to the EmailReadMessages function.

After importing an email message into FileMaker, pass any attachment paths to this function to get container data for the attachment path. For example, you might pass the following argument:

EmailReadAttachment(
    "/Macintosh HD/private/tmp/4545776.01203682301836.JavaMail.root@pluto.local/text.html"
)

The supplied path should not begin with file:, image:, or any other prefix - just the path.

Note that this will actually work for any file, it doesn't need to be an email attachment.

Parameters:

path
The path as returned in the email import
savePath
An optional path parameter to save the attachment to a local folder instead of a container field

Returns: container data for the file at path, or "ERROR" if an error occurred (use EmailLastError in this case)

EmailReadMessages ( { flag1 ; flag2 ; ... } )

Reads messages from the currently connected inbound mail server. After calling this function, you will typically use the EmailGetNextMessage function to iterate over the messages which were fetched. As an alternate approach, you can perform an XML import of the fetched message data, using the value returned from this function as the XML file path.

If an error occurs, this function will return "ERROR". Use the EmailLastError function to get more information about the error.

Fetching Unread Messages

The Email plugin supports reading messages from POP and IMAP mailboxes. Typically, you're interested in only fetching new messages from your mailbox. There are several approaches to doing this.

Option 1: Search by UID (IMAP or POP3)

Note: POP3 mail servers are not required to support UIDs. Please check with the server administrator about UID support. IMAP and POP3 mailboxes assign each message a unique UID. When reading messages from an IMAP or POP3 mailbox, you can get the value for this UID with the following function:

Set Field[ImportedMessage::uid ; EmailReadMessageValue( "uid" ) ]

Once you have the UID of the most recently fetched message, you can pass that in as an argument to subsequent calls to EmailReadMessages, for example:

Go To Record/Request/Page [Last]
Set Variable [ $result = EmailReadMessages (
    "uid=" & ImportedMessage::uid
)
]

This fetches only the messages whose UID is greater than the most recently fetched message. This is the preferred way to fetch new messages from a mailbox, as it is very efficient, doesn't modify any messages, and will work even if another email client accesses the mailbox.


Option 2: Search for Unread Messages

You can specify a filter option to only search for unread messages:

Set Variable [ $result = EmailReadMessages (
    "viewed=false" ;
    "readonly=false"
)
]

After fetching unread messages, you should then set the "viewed" flag to true for each message, so subsequent reads will skip these messages. This is outlined in the following section "Reading Individual Messages" Note: searching for unread messages will not work correctly if other email clients are accessing the same mailbox and marking messages as viewed.


Option 3: Skipping messages

This is similar to option 2, except you don't need to modify the messages on the server. Simple count how many messages have been fetched from the mailbox, and pass a skip parameter to the EmailReadMessages function whose value is this number. Note: If messages are deleted from the mailbox, local messages should be deleted as well, so the local count matches the number of fetched messages on the server.


Reading Individual Messages

After successfully calling EmailReadMessages, you can iterate over the fetched messages using the EmailGetNextMessage function. This pattern typically looks like this:

Loop
    Exit Loop If [not EmailGetNextMessage]
    New Record/Request
    Set Field[ImportedMessage::from ; EmailReadMessageValue( "from" )]
    Set Field[ImportedMessage::to ; EmailReadMessageValue( "to" )]
    Set Field[ImportedMessage::subject ; EmailReadMessageValue( "subject" )]
    Set Field[ImportedMessage::body ; EmailReadMessageValue( "body" )]
    Set Field[ImportedMessage::messageId ; EmailReadMessageValue( "messageId" )]
    // OPTIONAL: mark this messages as "viewed"
    // (You must pass readonly=false during EmailReadMessages to do this)
    Set Variable[$result ; EmailMessageSetFlag("viewed")]
End Loop

Importing Messages via XML

To import email data into FileMaker via XML, use the "Import Records" script step, and specify an XML data source, passing the file URL returned from this function.
Use the "messageId" field in the resulting XML as a match field when defining import options. Note: XML import is not a web-safe script. Use the method described in "Reading Individual Messages" if your script is running in IWP or on the server, or if you need to modify individual messages on the server.

Flags

This function accepts a variety of flags which allow you to fine-tune how the messages are read. Flags should be entered as key=value arguments. You can specify any number of flags you wish. The following is a description of the available flags:

progress
Whether to show a cancellable progress bar (default is false).
progressLocation
Location of the progress bar, e.g. "100,200". Default is centered on-screen.
mailbox
The name of the mailbox to read messages from (Note: this is only useful for IMAP accounts). The default behavior is to read messages from the INBOX.
attachments
Boolean flag indicating whether to download attachment data. The default value is true, which enables attachment downloading. Setting this to false will disable downloading attachments, which can be significantly faster. If attachment downloading is disabled, you can still retrieve a list of the attachments in a message using the EmailReadMessageValue ( "attachments" ) function. You can the re-read the message at a later time to download the attachments.

skip
Skip this many records before reading results. This is useful for fetching messages in batches, if you know that messages will not be deleted from a mailbox during reading.
max
Do not return more than this many records in the import
uid
(Note: not all POP3 mail servers support UIDs) only fetch messages whose uid is newer than the one passed in. This is very useful for only fetching new messages from IMAP mailboxes. When looping through new messages, call EmailReadMessageValue("uid") on the last message and save this to a field in your database. Then when fetching new messages, pass this uid in as a filter argument. Only newer messages will be returned. Note: if you specify this option and the mailbox is an IMAP mailbox, some of the other search filters (skip, to, from, date) will be ignored.
dateFrom
Filter messages to only return messages sent on or after a certain date (some IMAP mailboxes require an additional flag of "deleted=any" for EmailReadMessages to read emails using this parameter).
dateTo
Filter messages to only return messages sent on or before a certain date (some IMAP mailboxes require an additional flag of "deleted=any" for EmailReadMessages to read emails using this parameter).
from
Filter messages by from address
to
Filter messages by to address
subject
Filter messages by subject
messageId
Filter messages by messageId
body
Filter messages by body
viewed
Filter messages by their read/unread status. Pass true to return only previously viewed messages, false to return only unread messages.
flagged
Filter messages by their flagged status. Pass true to return only flagged messages, false to return only non-flagged messages.
deleted
Filter messages by their deleted status. Pass true to return only deleted messages, false to return only non-deleted messages The default is false, meaning deleted message will be excluded.

alternateDecoding
Use an alternate method of decoding retrieved emails. Please contact 360Works if you are unsure of when to use this parameter. Pass 1 to enable (e.g., "alternateDecoding=1"). The alternate decoding method is disabled by default

readonly
Whether to open the mailbox folder as readonly or read-write. The default is true (read-only). If you plan on deleting, moving, or flagging any messages, use false in this parameter. Note: setting readonly=false will cause any fetched messages to be marked as "viewed"!

For example, you might use the following to fetch the first 25 unread messages from your inbox:

EmailReadMessages(
    "mailbox=INBOX" ;
    "attachments=false" ;
    "max=25" ;
    "attachments=false" ;
    "viewed=false"
)


Parameters:

flags
optional flags which control how messages are read.

Returns: The URL of the local XML file. This URL can be passed to FileMaker as the XML data source location.

EmailReadMessagesFromFile ( file { ; charset=UTF-8 } )

This reads messages from an non-directory MBOX file or raw message content file (.eml), and stores the parsed messages in an FMPXML file, suitable for import into FileMaker. In addition, you can use the EmailGetNextMessage function after calling this to loop over the messages and programatically read individual values using the EmailReadMessageValue.

Flags

The following is a description of the available flags:

charset
Character set of the file. Leave this blank to use the default for your locale.

Note: this will disconnect from your current mail server if there is an active connection.

Parameters:

file
path to an MBOX file

Returns: URL to an FMPXML file containing the parsed messages in the file

EmailReadMessageValue ( key )

Retrieves information about the last message which was gotten by the EmailGetNextMessage function.

If there are multiple values for a key, each value will be on a separate line.

The parameter must be one of the following values (case-insensitive):

  • count (The total number of messages fetched from the server)
  • from (The FROM address)
  • to (The TO addresses, comma-separated)
  • cc (The CC addresses, comma-separated)
  • bcc (The BCC addresses, comma-separated)
  • replyTo (The reply-to address)
  • subject
  • messageNumber (the integer index of the message on the server. 1 is the first message in the mailbox)
  • sent (The timestamp the message was sent)
  • messageID (The unique message ID for the email message)
  • attachments (A return-separated list of attachments for the message. Each line is either the attachment file path, or the name, depending on the value of the attachments parameter in EmailReadMessages). Note: inlined attachments are excluded from this list. Use attachmentsAll to get all attachments including inlined ones.
  • text (The plain-text message content, if available)
  • html (The HTML body part, if one is available. If attachments are set to download, inline attachment images will be converted to base64 data URLs automatically. If you don't want this behavior, use htmlRaw instead, or set attachments=false when fetching messages.)
  • htmlRaw (The HTML body part unaltered, if one is available.)
  • uid (returns the IMAP or POP3 folder uid Note: not all POP3 mail servers support UIDs)
  • viewed (1 or empty to indicate whether the message has been read (1) or is unread)
  • flagged (1 or empty to indicate whether the message is flagged)
  • replied (1 or empty)
  • deleted (1 or empty)
  • header:HEADER_NAME (any header value, replace HEADER_NAME with the name of the header to retrieve)
  • headers (a return-separated list of all message headers)
  • raw: (the raw source of the entire message)

Reading Message Headers

You can retrieve any message header by using this function. For example, to get information about the mail application which sent the message, you can use EmailReadMessageValue("header:X-Mailer"). If a header has multiple values, they will be returned as a return-separated list.

Parameters:

key
The key to retrieve, must be one of the above listed keys.

Returns: The value for that key in the current message.

EmailVersion

Returns the version number of the Email plugin.

Returns: a text version number

IM_GetBuddyIcon ( service ; login ; password ; buddy )

Returns a buddy's icon. If the buddy doesn't have an icon set, a default one will be returned corresponding to the buddy's messaging service. Note that if a connection is made shortly before the function is called, the returned icon be the default even if the buddy does have one set. A subsequent call will return the appropriate icon after it has been retrieved and cached by the plugin.

Parameters:

service
the messaging service to use; currently only "AIM" is supported
login
login/account name for the service
password
the password for service account
buddy
the buddy whose icon to get

Returns: the buddy's icon as a container

IM_GetBuddyList ( service ; login ; password )

Connects to the messaging service (if necessary) and retrieves the user's buddy list. The list is return-separated and can easily be parsed using FileMaker's built-in GetValue() function.

Parameters:

service
the messaging service to use; currently only "AIM" is supported
login
login/account name for the service
password
the password for service account

Returns: return-separated list of buddies

IM_GetBuddyStatusMessage ( service ; login ; password ; buddy )

Returns a buddy's status. If the buddy doesn't have a status set, an empty string is returned instead. Note that if a connection is made shortly before the function is called, the returned status may still be blank even if the buddy does have one set. A subsequent call will return the status after it has been retrieved and cached by the plugin.

Parameters:

service
the messaging service to use; currently only "AIM" is supported
login
login/account name for the service
password
the password for service account
buddy
the buddy whose status to get

Returns: the buddy's current status; if no status is set, an empty string is returned

IM_GetBuddyStatusType ( service ; login ; password ; buddy )

Returns a buddy's status type as one of the following: "online", "idle", "away", "mobile", or "offline". If the buddy doesn't have a status set, an empty string is returned instead. Note that if a connection is made shortly before the function is called, the returned status type may still be blank even if the buddy does have one set. A subsequent call will return the status type after it has been retrieved and cached by the plugin.

Parameters:

service
the messaging service to use; currently only "AIM" is supported
login
login/account name for the service
password
the password for service account
buddy
the buddy whose status type to get

Returns: the buddy's current status type

IsValidEmail ( email )

Convenience function for validating an email address. This checks for conformance to RFC 822, but does not actually check that an active email account exists at this address.

Parameters:

email
one or more email addresses to validate (comma-separated).

Returns: 1 if the all emails are valid, 0 if any address is invalid, or "" if email is empty.
Retrieved from "http://docs.360works.com/index.php?title=360Works_Email/Documentation&oldid=2252"
Personal tools
Namespaces

Variants
Actions
Plug-in Products
Other Products
Navigation
Toolbox