TweetFollow Us on Twitter

Introduction to Scripting Mail

Volume Number: 21 (2005)
Issue Number: 9
Column Tag: Programming

AppleScript Essentials

Introduction to Scripting Mail

by Benjamin S. Waldie

Email automation is usually popular among AppleScript developers using Mac OS X. By writing scripts to perform email-related processes, developers can automate processes such as sending batches of recipient-customized messages, archiving emails in text format or in a database, emailing status reports to administrators, and much more.

In this month's article, we will discuss using AppleScript to automate aspects of the Mail application, which comes pre-installed with OS X. If you don't use the Mail application, then you may want to explore some of the many other scriptable email clients and tools that are available for the Mac. Some of these will be mentioned later in this article.

Working with Accounts

In Mail, as with most email applications, users may have multiple email accounts, all with specific settings and configurations. AppleScript can actually be used to interact with these accounts, allowing you to automate the process of configuring accounts, retrieving account settings, and more.

Accessing Accounts

Let's get started by writing some code that will retrieve the name of every account in Mail, regardless of its type.

tell application "Mail"
   name of every account
end tell
—> {"AppleScriptGuru"}

For users that have multiple types of email accounts, the following example code will allow you to determine the exact class of a given account. Possible classes include imap, pop, smtp, and Mac.

tell application "Mail"
   account type of account "AppleScriptGuru"
end tell
—> Mac

The account class, along with a listing of its properties, can be found in the Message suite in Mail's AppleScript dictionary. Additional account properties are type specific, and are listed under the following separate classes, which inherit most of their properties from the main account class - Mac account, imap account, and pop account. See figure 1.


Figure 1. Account Classes in Mail

The following code will retrieve a listing of all .Mac accounts.

tell application "Mail"
   name of every Mac account
end tell
—> {"AppleScriptGuru"}

Accounts possess a number of other properties, which are accessible through scripting. While some properties of an account are read only, such as account type and password, others may be retrieved and adjusted by way of scripting. The following example code will retrieve all of the properties of a specified account.

tell application "Mail"
   properties of account "AppleScriptGuru"
end tell
—> {account type:Mac, compact mailboxes when closing:true, 
           empty trash on quit:false, move deleted messages to trash:true, 
           account directory:"/Users/bwaldie/Library/Mail/Mac-applescriptguru"...

Disabling Accounts

In some cases, you may have the need to disable an account entirely. In order to do this manually in Mail, you must do so by opening the Preferences window, navigating to the proper account, and deselecting a checkbox in a specific location. To disable multiple accounts, you would need to repeat this process for each account. However, this task can easily be automated with AppleScript.

The following example code demonstrates how to disable an account in Mail. To re-enable the account, simply change the false value to true.

tell application "Mail"
   set enabled of account "AppleScriptGuru" to false
end tell

It is important to note that, when disabling account with AppleScript, the account will automatically become re-enabled the next time Mail is launched.

Setting Account Passwords

As previously mentioned, most properties of an account can be modified via scripting, including the password for the account. The following code demonstrates how to change the password for an account.

tell application "Mail"
   set password of account "AppleScriptGuru" to "myPass"
end tell

For obvious reasons, AppleScript cannot be used to retrieve the password for an account.

tell application "Mail"
   password of account "AppleScriptGuru"
end tell
—> "Account passwords can only be set, not read."

Accessing SMTP Servers

When configuring an account, you may also need to configure its SMTP server. The following code shows how to retrieve a reference to the SMTP server of an account.

tell application "Mail"
   smtp server of account "AppleScriptGuru"
end tell
—> smtp server "smtp.mac.com:applescriptguru" of 
application "Mail"

Like an account, an smtp server is actually a class in Mail, and therefore, it possesses properties, many of which are modifiable.

tell application "Mail"
	set theSMTPServer to smtp server of account "AppleScriptGuru"
	properties of theSMTPServer
end tell
—> {account type:smtp, authentication:none, server name:"smtp.mac.com", ...

The following example code demonstrates how to retrieve a list of all SMTP servers in Mail.

tell application "Mail"
   every smtp server
end tell
—> {smtp server "smtp.mac.com:applescriptguru" of 
application "Mail"...

Working with Messages

While interacting with accounts may be beneficial for some, interacting with messages directly via AppleScript is probably a much more applicable topic to most. In Mail, AppleScripts may be written to generate and send new messages, retrieve information about messages, and more. First, we will discuss outgoing messages.

Generating an Outgoing Message

The following code demonstrates how to generate a new outgoing message. You will see that, during the creation of the outgoing message, I have chosen to assign values to certain properties of the message, including the message's subject and body.

tell application "Mail"
   make new outgoing message with properties {visible:true, subject:"My Subject", content:"My Body"}
end tell
—> outgoing message id 137230944of application "Mail"

In the code above, I also specified a value for the visible property of the outgoing message. The reason for this is that, by default, Mail will create new outgoing messages without displaying them. This makes it possible for you to write scripts that generate a new email message, without displaying the message to the user.

Adding an Attachment to an Outgoing Message

You may have noticed in the previous examples that, when creating a new message, a reference to the new message is returned as the result of the make command. Like any result, this reference can be placed into a variable, allowing you to continue referring to the new message.

One example of when this may be beneficial is when you want to insert an attachment into an outgoing message. In Mail, an attachment is not actually considered an element of a message. Rather, it is considered an element of the content of a message. Therefore, to insert an attachment into a message, you must tell the message to make an attachment within its content. The following example code demonstrates this process.

set theAttachment to choose file
tell application "Mail"
   set theMessage to make new outgoing message with properties {visible:true, 
   subject:"My Subject", content:"My Body"}
   tell content of theMessage
      make new attachment with properties {file name:theAttachment} at after last paragraph
   end tell
end tell

Adding Recipients to an Outgoing Message

So far, we have discussed creating a new message with a subject and body, and adding attachments. However, in order to send an outgoing message, you will also need to insert recipients. In Mail, outgoing messages may contain the following recipient classes as elements - bcc recipient, cc recipient, and to recipient.

The following example code demonstrates how to add a new to recipient to an outgoing message. A similar process may be used to add a new cc or bcc recipient.

tell application "Mail"
   set theMessage to make new outgoing message with properties 
      {visible:true, subject:"My Subject", content:"My Body"}
   tell theMessage
      make new to recipient at end of to recipients with properties 
         {name:"Ben Waldie", address:"applescriptguru@mac.com"}
   end tell
end tell

To add multiple recipients, you would use a repeat loop to continue creating new recipients at the end of the existing recipients.

Sending an Outgoing Message

Sending an outgoing message in Mail is very straightforward, and is done by using the send command.

send theMessage

Accessing Messages

In addition to generating and sending messages, you may want to write scripts that interact with messages that you have received. These messages may be located within your inbox, or within another mailbox. The following code may be used to retrieve the selected messages in Mail.

tell application "Mail"
   selection
end tell
—> {message 15 of mailbox "INBOX" of account "AppleScriptGuru" of application "Mail"}

You may notice, in the example above, that the result is an AppleScript list. This is because you may have multiple messages selected in Mail. Therefore, when retrieving the selection, you will most likely want to loop through the returned list of messages, processing each message appropriately.

Optionally, you may refer to a message by its index in a specific mailbox. For example, the following code refers to the first message of a given account in my inbox.

set theMessage to message 1 of mailbox "INBOX" of account "AppleScriptGuru"

Likewise, the following code refers to the first message in a locally created mailbox.

set theMessage to message 1 of mailbox "Filed" 

Reading Messages

Once you have generated a reference to a message in Mail, you can retrieve any of its properties. The following example code demonstrates how to retrieve the subject of the first selected message.

tell application "Mail"
   set theSelection to selection
   set theMessage to item 1 of theSelection
   subject of theMessage
end tell
—> "My Message Subject"

The following example code demonstrates how to retrieve the body of the first selected message.

tell application "Mail"
   set theSelection to selection
   set theMessage to item 1 of theSelection
   content of theMessage
end tell
—> "My Message Body"

Messages have numerous other properties that can be retrieved, if desired, including date sent, source (useful for HTML-based messages), and sender. Some properties of messages can also be changed with AppleScript, including the message's flagged status, junk status, and read status.

In addition to properties, messages may also contain recipients as elements, which can also be retrieved. The following example code demonstrates how to retrieve a list of the to recipients of a message.

tell application "Mail"
   set theSelection to selection
   set theMessage to item 1 of theSelection
   set theRecipients to to recipients of theMessage
end tell
—> {to recipient 1 of message 15 of mailbox "INBOX" of account 
   "AppleScriptGuru" of application "Mail"}

Once retrieved, you can loop through the recipients, retrieving any desired properties of those recipients.

properties of item 1 of theRecipients
—> {name:"Ben Waldie", address:"applescriptguru@mac.com", class:recipient}

Retrieving Message Attachments (Tiger Only!)

In Mail, retrieving attachments has always been a difficult task, and until the release of Mac OS X Tiger, it was all but impossible without some roundabout, complex scripting. In Tiger, there is finally a way to do it.

The following example code demonstrates how to save the attachments of a message into a specified folder.

set theOutputFolder to (choose folder) as string
tell application "Mail"
   set theMessages to selection
   set theMessage to item 1 of theMessages
   set theAttachments to every attachment of content of theMessage
   repeat with a from 1 to length of theAttachments
      set theAttachment to item a of theAttachments
      try
         set theAttachmentName to name of theAttachment
         set theSavePath to theOutputFolder & theAttachmentName
         save theAttachment in theSavePath
      end try
   end repeat
end tell

Filing a Message

Filing a message in a mailbox is not done by using the move command, as one might expect. Rather, to file a message, you must change the mailbox property of the message to a specified mailbox.

The following example code would file the specified message into a local mailbox named Filed.

tell application "Mail"
   set theSelection to selection
   set theMessage to item 1 of theSelection
   set mailbox of theMessage to mailbox "Filed"
end tell

Triggering Scripts from a Rule

One very useful feature in Mail is the ability to trigger an AppleScript from a rule. This can enable you to create a fully automated workflow to process incoming email messages. For example, you could write a script that will automatically send a customized thank you email to anyone who subscribes to your mailing list.

Writing a Mail Rule Script

A script that will be triggered as a Mail rule may be saved in a variety of ways, including as a compiled script, as text, or as an application. The main requirement is that the script must contain a perform mail action handler, which will be triggered by Mail when the rule processes on messages. This handler may be written in one of two manners.

on perform_mail_action(theData)
   tell application "Mail"
      set theSelectedMessages to |SelectedMessages| of theData
      set theRule to |Rule| of theData
      repeat with a from 1 to count theSelectedMessages
         — Process the current message
      end repeat
   end tell
end perform_mail_action

In the example above, the handler's positional parameter, in this case theData (the parameter name may be set to any variable name desired), contains a record. This record contains 2 properties, |SelectedMessages| and |Rule|, which will be automatically populated by Mail with a list of messages on which the rule is triggered, as well as a reference to the rule itself. Using this information, you can write custom code to perform the desired tasks on the passed list of messages, or to retrieve information about the rule that was triggered.

The following is a second example of how the perform mail action handler may be written.

using terms from application "Mail"
   on perform mail action with messages theSelectedMessages for rule theRule
      repeat with a from 1 to count theSelectedMessages
         — Process the current message
      end repeat
   end perform mail action with messages
end using terms from

In the handler example above, you will notice that the parameters are specified individually as labeled parameters, rather than in a single positional parameter containing a record.

Again, either of the above handlers may serve as a Mail rule script. You may choose to use whichever you feel the most comfortable using.

Configuring a Mail Rule Script

Once you have written your Mail rule script, you will need to configure Mail to trigger it on incoming messages. To do so, open Mail's Preferences window, and click on Rules in the window's toolbar.

Next, click the Add Rule button, and configure the new rule to trigger according to the desired criteria. Finally, configure the rule to perform the Run AppleScript action, and specify the path to your saved Mail rule script. Figure 2 shows an example of a configured Mail rule script.


Figure 2. A Configured Mail Rule Script

Now, you are ready to begin using the rule to process messages with your script. The rule will be automatically triggered when incoming messages matching the specified criteria are detected. You may also trigger the rule manually on selected messages by selecting Apply Rules from the Message menu.

Other Options

As mentioned at the beginning of this article, there are a number of other Macintosh-based email applications and tools, which are also AppleScriptable. If you prefer not to use Mail, you are encouraged to explore these other options. The following are a handful of scriptable email clients and tools.

Microsoft's Entourage is a very scriptable commercial email client, which, in addition to offering email capabilities, also offers an integrated calendar, task list, address book, and more. Information about Entourage, along with other Macintosh-compatible Microsoft applications, can be found on Microsoft's website at http://www.microsoft.com/mac/.

Eudora, by QUALCOMM Incorporated, is another popular email client, which has great support for AppleScript. Eudora is available for free in Light mode, and is also available with additional features in Sponsored or Paid mode. General information about Eudora can be found on the main Eudora website at http://www.eudora.com. Information about Eudora's AppleScript support may be found at http://www.eudora.com/developers/scripting. html.

Xmail.osax is a Mac OS X scripting addition, written by Jean-Baptiste LE STANG. This scripting addition offers AppleScript developers a quick and easy way to send (not receive) email messages, without the need for an email client. This scripting addition can be great for scripts that need to send regular progress reports through email. Information about Xmail.osax, along with a download link, can be found on Jean-Baptiste LE STANG's website at http://lestang.org.

In Closing

Now that you have some idea of the types of tasks you can automate with Mail, you are encouraged to begin exploring Mail's AppleScript dictionary further. There are many other tasks that can be automated with Mail, which were not covered in this article. Basic information about Mail scripting, including an overview of sample Mail scripts that are included with OS X, can be found on Apple's website at http://www.apple.com/applescript/mail/. If you are looking for pre-existing scripts for Mail, or for other email clients, be sure to check out MacScripter.net's ScriptBuilders section at http://scriptbuilders.net/.

Until next time, keep scripting!


Ben Waldie is author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from http://www.spiderworks.com. Ben is also president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit http://www.automatedworkflows.com, or email Ben at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

coconutBattery 3.9.14 - Displays info ab...
With coconutBattery you're always aware of your current battery health. It shows you live information about your battery such as how often it was charged and how is the current maximum capacity in... Read more
Keynote 13.2 - Apple's presentation...
Easily create gorgeous presentations with the all-new Keynote, featuring powerful yet easy-to-use tools and dazzling effects that will make you a very hard act to follow. The Theme Chooser lets you... Read more
Apple Pages 13.2 - Apple's word pro...
Apple Pages is a powerful word processor that gives you everything you need to create documents that look beautiful. And read beautifully. It lets you work seamlessly between Mac and iOS devices, and... Read more
Numbers 13.2 - Apple's spreadsheet...
With Apple Numbers, sophisticated spreadsheets are just the start. The whole sheet is your canvas. Just add dramatic interactive charts, tables, and images that paint a revealing picture of your data... Read more
Ableton Live 11.3.11 - Record music usin...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... Read more
Affinity Photo 2.2.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
SpamSieve 3.0 - Robust spam filter for m...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
WhatsApp 2.2338.12 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Fantastical 3.8.2 - Create calendar even...
Fantastical is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun: Open Fantastical with a single click or keystroke Type in your event details... Read more
iShowU Instant 1.4.14 - Full-featured sc...
iShowU Instant gives you real-time screen recording like you've never seen before! It is the fastest, most feature-filled real-time screen capture tool from shinywhitebox yet. All of the features you... Read more

Latest Forum Discussions

See All

The iPhone 15 Episode – The TouchArcade...
After a 3 week hiatus The TouchArcade Show returns with another action-packed episode! Well, maybe not so much “action-packed" as it is “packed with talk about the iPhone 15 Pro". Eli, being in a time zone 3 hours ahead of me, as well as being smart... | Read more »
TouchArcade Game of the Week: ‘DERE Veng...
Developer Appsir Games have been putting out genre-defying titles on mobile (and other platforms) for a number of years now, and this week marks the release of their magnum opus DERE Vengeance which has been many years in the making. In fact, if the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 22nd, 2023. I’ve had a good night’s sleep, and though my body aches down to the last bit of sinew and meat, I’m at least thinking straight again. We’ve got a lot to look at... | Read more »
TGS 2023: Level-5 Celebrates 25 Years Wi...
Back when I first started covering the Tokyo Game Show for TouchArcade, prolific RPG producer Level-5 could always be counted on for a fairly big booth with a blend of mobile and console games on offer. At recent shows, the company’s presence has... | Read more »
TGS 2023: ‘Final Fantasy’ & ‘Dragon...
Square Enix usually has one of the bigger, more attention-grabbing booths at the Tokyo Game Show, and this year was no different in that sense. The line-ups to play pretty much anything there were among the lengthiest of the show, and there were... | Read more »
Valve Says To Not Expect a Faster Steam...
With the big 20% off discount for the Steam Deck available to celebrate Steam’s 20th anniversary, Valve had a good presence at TGS 2023 with interviews and more. | Read more »
‘Honkai Impact 3rd Part 2’ Revealed at T...
At TGS 2023, HoYoverse had a big presence with new trailers for the usual suspects, but I didn’t expect a big announcement for Honkai Impact 3rd (Free). | Read more »
‘Junkworld’ Is Out Now As This Week’s Ne...
Epic post-apocalyptic tower-defense experience Junkworld () from Ironhide Games is out now on Apple Arcade worldwide. We’ve been covering it for a while now, and even through its soft launches before, but it has returned as an Apple Arcade... | Read more »
Motorsport legends NASCAR announce an up...
NASCAR often gets a bad reputation outside of America, but there is a certain charm to it with its close side-by-side action and its focus on pure speed, but it never managed to really massively break out internationally. Now, there's a chance... | Read more »
Skullgirls Mobile Version 6.0 Update Rel...
I’ve been covering Marie’s upcoming release from Hidden Variable in Skullgirls Mobile (Free) for a while now across the announcement, gameplay | Read more »

Price Scanner via MacPrices.net

New low price: 13″ M2 MacBook Pro for $1049,...
Amazon has the Space Gray 13″ MacBook Pro with an Apple M2 CPU and 256GB of storage in stock and on sale today for $250 off MSRP. Their price is the lowest we’ve seen for this configuration from any... Read more
Apple AirPods 2 with USB-C now in stock and o...
Amazon has Apple’s 2023 AirPods Pro with USB-C now in stock and on sale for $199.99 including free shipping. Their price is $50 off MSRP, and it’s currently the lowest price available for new AirPods... Read more
New low prices: Apple’s 15″ M2 MacBook Airs w...
Amazon has 15″ MacBook Airs with M2 CPUs and 512GB of storage in stock and on sale for $1249 shipped. That’s $250 off Apple’s MSRP, and it’s the lowest price available for these M2-powered MacBook... Read more
New low price: Clearance 16″ Apple MacBook Pr...
B&H Photo has clearance 16″ M1 Max MacBook Pros, 10-core CPU/32-core GPU/1TB SSD/Space Gray or Silver, in stock today for $2399 including free 1-2 day delivery to most US addresses. Their price... Read more
Switch to Red Pocket Mobile and get a new iPh...
Red Pocket Mobile has new Apple iPhone 15 and 15 Pro models on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide service using all the major... Read more
Apple continues to offer a $350 discount on 2...
Apple has Studio Display models available in their Certified Refurbished store for up to $350 off MSRP. Each display comes with Apple’s one-year warranty, with new glass and a case, and ships free.... Read more
Apple’s 16-inch MacBook Pros with M2 Pro CPUs...
Amazon is offering a $250 discount on new Apple 16-inch M2 Pro MacBook Pros for a limited time. Their prices are currently the lowest available for these models from any Apple retailer: – 16″ MacBook... Read more
Closeout Sale: Apple Watch Ultra with Green A...
Adorama haș the Apple Watch Ultra with a Green Alpine Loop on clearance sale for $699 including free shipping. Their price is $100 off original MSRP, and it’s the lowest price we’ve seen for an Apple... Read more
Use this promo code at Verizon to take $150 o...
Verizon is offering a $150 discount on cellular-capable Apple Watch Series 9 and Ultra 2 models for a limited time. Use code WATCH150 at checkout to take advantage of this offer. The fine print: “Up... Read more
New low price: Apple’s 10th generation iPads...
B&H Photo has the 10th generation 64GB WiFi iPad (Blue and Silver colors) in stock and on sale for $379 for a limited time. B&H’s price is $70 off Apple’s MSRP, and it’s the lowest price... Read more

Jobs Board

Optometrist- *Apple* Valley, CA- Target Opt...
Optometrist- Apple Valley, CA- Target Optical Date: Sep 23, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 796045 At Target Read more
Senior *Apple* iOS CNO Developer (Onsite) -...
…Offense and Defense Experts (CODEX) is in need of smart, motivated and self-driven Apple iOS CNO Developers to join our team to solve real-time cyber challenges. Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Child Care Teacher - Glenda Drive/ *Apple* V...
Child Care Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Share on Facebook Apply Read more
Machine Operator 4 - *Apple* 2nd Shift - Bon...
Machine Operator 4 - Apple 2nd ShiftApply now " Apply now + Start apply with LinkedIn + Apply Now Start + Please wait Date:Sep 22, 2023 Location: Swedesboro, NJ, US, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.