AppleScripts for Marking Messages as Read in Mac Mail

At the request of MacSparky, I've put together a few AppleScirpts for Mac Mail users, to mark messages as unread...

Script 1: Mail • Mark All Inbox Messages Read

tell application "Mail"
     set read status of every message of inbox to true
end tell

Script 2: Mail • Mark All Messages Read

display alert "Please note!" message "This script may take a while if you have a ton of mailboxes. Do you want to continue?" buttons {"Cancel", "Yes"} cancel button "Cancel"

with timeout of  600 seconds
     tell application "Mail"
          set read status of every message of inbox where its read status = false to true
          set read status of every message of every ¬
               mailbox where its read status = false to true
          set read status of every message of every mailbox ¬
               of every account where its read status = false to true
     end tell
end timeout

Script 3: Mail • Mark Selected Mailbox Messages Read

display alert "Please note!" message "This script may take a while if you have a lot of mailboxes selected. Do you want to continue?" buttons {"Cancel", "Yes"} cancel button "Cancel"

set processSubMailboxes to (button returned of (display alert "Would you like to scan all submailboxes too?" message "Again, if you have a lot of selected mailboxes and submailboxes, this may take a while." buttons {"Yes", "No"})) = "Yes"

tell application "Mail"
     tell front message viewer
          set theSelectedMailboxes to selected mailboxes
          repeat with a from 1 to length of theSelectedMailboxes
               set theCurrentMailbox to item a of theSelectedMailboxes
               processMailbox(theCurrentMailbox, processSubMailboxes) of me
          end repeat
     end tell
end tell

on processMailbox(theMailbox, processSubMailboxes)
     tell application "Mail"
          if processSubMailboxes = true then
               set theSubMailboxes to every mailbox of theMailbox
               repeat with a from 1 to length of theSubMailboxes
                    set theCurrentSubMailbox to item a of theSubMailboxes
                    processMailbox(theCurrentSubMailbox, processSubMailboxes) of me
               end repeat
          end if
          set read status of every message of theMailbox to true
     end tell
end processMailbox

Usage

You can download these scripts here.

You can quickly and easily run them from the system-wide AppleScript menu.  This menu is not enabled by default.  To enable it and install the scripts...

  1. Launch AppleScript Editor in /Applications/Utilities
  2. Select AppleScript Editor > Preferences from the menu bar
  3. Under General, click the Show Script Menu in the Menu Bar checkbox
  4. Bring Mail to the front
  5. From the script menu, choose Open Scripts Folder > Open Mail Scripts Folder
  6. Copy the scripts into the folder.  They will now be available from the script menu when you're working in Mail

Enjoy!

-Ben

What not to do in Mac Mail

Here's a handy data loss prevention tip.  With a Mail message selected, do not press either of the secret undocumented keyboard shortcuts Option+Control+H or  Command+Option+Control+H.  That is, unless you want your selected message irretrievably deleted.  Not moved to the trash.  Deleted.  Permanently.

Tested in Mac OS X 10.7.3. Bug report filed.

Note: If you're backing your Mac up with Time Machine, as you should be, then you may be able to restore the vaporized message.

10 Mac OS X Productivity Tips for Open and Save Dialogs

They're open and save dialogs. You navigate to a file or folder. You select it.  You enter a file name when saving.  You click Open or Save.  How much more efficient can you get? Well, here are 10 things most Mac users probably don't know...

Tip 1: Drag and drop a file or a folder right from the Finder into the open or save dialog to quickly select it.  If you do this in a save dialog with a file, then the file's name is automatically entered as the save name.

Tip 2: With a folder or file selected in the dialog, press Command+R to bring the Finder to the front and reveal the item.

Tip 3: To manually navigate to a folder, press Command+Shift+G (or / or ~).  Enter the desired path.  As you type it in, you can press tab to auto-complete folder names.

Tip 4: To see hidden files and folders, press Command+Shift+Period (>).

Tip 5: To quickly navigate to:

  • The Desktop - Press Command+D
  • The Documents Folder - Press Command+Shift+O
  • The Downloads Folder - Press Command+Shift+L
  • The Applications Folder- Press Command+Shift+A
  • The Home Folder - Press Command+Shift+H

Hint: The other navigation keyboard shortcuts in the Finder's Go menu should work here too.

Tip 6: To create a new folder, press Command+Shift+N.

Tip 7: To navigate up one level, press Command+Shift+Up Arrow Key

Tip 8: To choose an image, audio track, or movie, click Media in the sidebar.

Tip 9: To move a file or folder displayed in an open or save dialog to another folder, open the target folder in the Finder.  Then, drag the item from the open or save dialog into the opened folder window in the Finder.

Tip 10: With a file or folder selected, press Command+I to bring the Finder to the front and display the Get Info window for the item.

So, there you have it. Small tips that will save you a few precious seconds here and there and make you more productive.  Every second counts, right?

Now Available: New Mac Automation Made Simple Videos!

Peachpit has bundled a new series of my Mac Automation Made Simple videos on Automator.  They're now available for purchase as DRM-Free downloads, so you can play them on your Mac, iPhone, or iPad.  Topics in this 8-part series include:

  • Automate generating job folders - If you use job folders for multiple projects to keep organized, learn how to save time and reduce errors by building workflows in Automator to create job folders consistently and quickly. You'll also learn the basics of actions and variables in Automator.
  • Batch-create folders from an Excel list - If your workflow ever requires you to create a large number of folders or sets of subfolders with specific naming conventions, Excel and Automator can work together to eliminate the manual creation of folders. By using the powerful features in Excel to build lists of file names in large numbers and use Automator to process those lists into hundreds of folders in minutes.
  • Display Growl notifications for new content - File sharing over a network is great for larger files that you wouldn't send via email, but how can you be sure that you're always notified when a new file lands in your folder? Learn how to team Automator with the popular notification software Growl to build a great workflow that eliminates the need for you to get an email or phone call notifying you of new files.
  • Schedule backups via a network - Do you manually back up your Mac to a server? If so, you've probably had to set up calendar reminders and run through the process on a regular basis or risk losing your data. In this lesson, learn how to make that process automatic and painless with Automator and iCal.
  • Share files via Dropbox - Take the powerful PDF tools offered in OS X a step further by building your own Print Plugin with Automator. You'll learn how to set up a Print Plugin that automatically posts any document you print to PDF to the online file sharing tool Dropbox. You'll also learn the basics of setting up actions to rename files to be friendly for upload tools by removing offending characters.
  • Batch-convert image files to PDF - If you've ever had the daunting task of scanning a book or a box of images with a flat bed scanner, you know that it isn't easy to combine all those files into a single PDF without some heavy-hitting applications like Photoshop and Acrobat Pro. But what if you don't have those applications or are just looking for an easier way? Learn how to set up a quick and easy way to combine multiple images into a single PDF without the hassle.
  • Batch-process images for iPhoto - If you're like most people with a smart phone, an amature photographer or have a large photo digitizing project on your plate, you'll import, manipulate and save hundreds to thousands of images a year. In this lesson, you'll learn how to unleash the power of Automator and free third-party tool to streamline your workflow and make importing images to your iPhoto library a snap.
  • Batch-process multiple InDesign files to PDF - Exporting multiple InDesign files to PDF can be as quick and easy as dragging and dropping your files. You'll learn how to create a drag-and-drop application with AppleScript and Automator that opens, exports, names, and saves PDFs from InDesign. You'll be able to use the same custom application for both InDesign CS4 and CS5.

Sold as a set, or individually, you can find them on Peachpit's website.

Mac Power Users Podcast Episode 070 – Working with Automator

I recently spoke with Katie Floyd and David Sparks about the automation capabilities in Mac OS X for episode 070 of the Mac Power Users podcast.  Topics included getting started with Automator, troubleshooting Automator workflows, Services, and differences between AppleScript and Automator.  Check it out on the Mac Power Users website or in iTunes!

Mac OS X Lion: The Missing Manual Details Services, Automator, and AppleScript

From the Acknowledgements page...

"Ben Waldie… did a beautiful job updating the Automator/AppleScript material in Chapter 7"
- David Pogue

"Thank you, David, for the opportunity to contribute to such a complete resource on the world's greatest operating system!"
-Ben Waldie

Looking for a great comprehensive book on Mac OS X, which covers everything including powerful built-in automation tools such as Services, Automator, and AppleScript? Look no further. Get your copy today!

Mac OS X Lion: The Missing Manual
David Pogue

With Lion, Apple has unleashed the most innovative version of Mac OS X yet—and once again, David Pogue brings his humor and expertise to the #1 bestselling Mac book. Mac OS X 10.7 completely transforms the Mac user interface with multi-touch gestures borrowed from the iPhone and iPad, and includes more than 250 brand-new features. This book reveals them all with a wealth of insight and detail--and even does a deep dive into iCloud, Apple's wireless, free syncing service for Macs, PCs, iPhones, and iPads.

  • Perfect for newcomers. Get crystal-clear, jargon-free introduction to the Dock, the Mac OS X folder structure, Safari, Mail, and iCloud.
  • Go in-depth. Learn how use key new features such as full-screen apps, Mission Control, the new Mac App Store, Launchpad, Resume, Auto Save, Versions, AirDrop, and more. Are you even more of a power user? Learn to set up a network, make a Lion flash drive, and even learn the basics of Lion's underlying Unix.

There's something new on practically every page of this new edition, and David Pogue brings his celebrated wit and expertise to every one of them. Apple's brought a new cat to town, and Mac OS X Lion: The Missing Manual is the best way to tame it.

About David Pogue

David Pogue is the personal-technology columnist for the New York Times. Each week, he contributes a print column, an online column and an online video. His daily blog, "Pogue's Posts," is the Times's most popular blog. David is also an Emmy award-winning tech correspondent for CBS News and a frequent guest on NPR's "Morning Edition." His trademark comic tech videos appear each Thursday morning on CNBC. With over 3 million books in print, David is one of the world's bestselling how-to authors. He launched his own series of complete, funny computer books called the Missing Manual series, which now includes 60 titles. David graduated summa cum laude from Yale in 1985, with distinction in Music, and he spent ten years conducting and arranging Broadway musicals in New York. He's been profiled on both "48 Hours" and "60 Minutes."

About Ben Waldie

Ben Waldie is president of Automated Workflows, LLC, a company offering AppleScript, Automator, and workflow consulting services to Mac-based businesses. For years, Ben has developed professional automated solutions for companies such as Abercrombie & Fitch, Adobe Systems, Apple Inc., CNN, Microsoft, NASA, PC World, and Time Magazine. Ben is the author of “Automator for Mac OS X: Visual QuickStart Guide" (Peachpit Press) and “AppleScripting the Finder" (Automated Workflows, LLC), has written content for Apple.com, Macworld, MacTech, MacScripter.net, and more, and is the host of the “Mac Automation Made Simple" video podcast series (Peachpit Press). Ben is also the author of an AppleScript training CD for the Virtual Training Company, and is a frequent presenter at Macworld and other industry events.

Developer Tip > Saving Mail Attachments via AppleScript Fixed in Lion 10.7.2

If you use AppleScripts that interact with Mail in Mac OS X (such as Mail to FileMaker Importer), you may have noticed that when Lion was introduced, the ability to save attachments through scripting no longer worked.  This issue affected AppleScripts, as well as Automator workflows (Apple's own Get Attachments from Mail Messages Automator action was broken too).  Well, I'm pleased to say that this issue has been resolved in Mac OS X 10.7.2.  AppleScripts can now save Mail attachments again.

If you'd like to learn more about AppleScripting Mail, check out my MacTech column... Introduction to Scripting Mail.

Attention Outlook Users: Saving attachments via AppleScript did not work in Outlook either until a recent Office update.  If your Outlook scripts are failing when attempting to save attachments, make sure you update your Office 2011 installation to the latest version.  While I don't have an article available at this time for scripting Outlook, you can learn about scripting Entourage in my MacTech column... Introduction to Scripting Microsoft Entourage.  The AppleScript terminology hasn't changed too much between Entourage and Outlook, so some of it may still apply.

Adobe Illustrator Automator Action Pack Updated to v1.07

The Adobe Illustrator Automator Action Pack (now version 1.07) has been updated to allow .ait documents to be opened.  The Ultimate Productivity Automator Action Pack (now version 3.19) has been updated to incorporate this change, as well.

More info or download a demo of the actions...

Sandboxing a Cocoa-AppleScript (AppleScriptObjC) Application

If you're a Mac developer, then you are probably aware that Apple will soon be requiring all applications submitted to the Mac App Store be sandboxed.  A sandboxed AppleScript-based application is kind of an oxymoron. Sandboxing denotes that an application will run in its own isolated environment, for security reasons.  Meaning that it doesn't have access to other applications on your Mac.  However, this goes against the nature of AppleScript, which is designed as an inter-application scripting language.  By writing AppleScripts, you can intertwine your various applications together to form complex workflows and automate time consuming things you would otherwise need to do manually.

So, how can you, an AppleScript developer, deal with sandboxing and get your app into the Mac App Store?  You can request temporary entitlements (translation: may not be supported in the future) for the apps and processes with which your app interacts.  Here are the general steps, which will vary depending on the actual function of your app:

1. Use Xcode to create your Cocoa-AppleScript app (AppleScriptObjC app)

2. In the Project Navigator, select your project

3. In the Project Editor, select your app's target

4. In the Summary tab, configure the following settings:

click to enlarge

- Enable Entitlements - Select this checkbox to turn entitlements on for your app

- App Sandbox - Select this checkbox to turn sandboxing on for your app

- File System - If you plan to use file/folder user interaction commands, such as "choose file", "choose folder", and "choose file name", then set this dropdown to "Read/Write Access".  Do the same if you plan to use commands such as "open for access" and "write".

5. In the Project Navigator, select the .entitlements file that should have been created automatically

6. Add an entry for "com.apple.security.temporary-exception.apple-events".  If you will have multiple entitlements, set this to be an array. Otherwise, set it to a string.  Add UTI entries for each application your app needs to target. For example, for the Finder, add "com.apple.finder". For iTunes, add "com.apple.itunes". If you don't add a temporary Apple Events entitlement and the necessary UTIs, then your app will produce errors when attempting to target external applications.

click to enlarge

7. If your app will write to a directory in the user's home folder, add an entry for "com.apple.security.temporary-exception.files.home-relative-path.read-write".  Set this to be an array, and add paths to any folders you will write to, beginning each with a slash. I.e. /Desktop/ represents the user's Desktop.

That should do it.  Build and run your project, and check Xcode's debug console for problems.

Download an example of a sandboxed Cocoa-AppleScript Xcode project here.

Official documentation for sandboxing an app can be found on Apple's developer website.

Note that sandboxing doesn't affect strictly AppleScript applications.  Other applications could potentially be affected, as well, including Automator* and numerous popular third-party applications.  Well, to be fair, these applications could still work.  They just couldn't be submitted to the Mac App Store once Apple's sandboxing requirement goes into effect, at least not without employing temporary entitlements.

For more on the growing controversy regarding sandboxing and inter-application communication, check out:

* In theory, Automator actions contained within a sandboxed application should not need to be sandboxed themselves.  This is because they would technically fall under the scope of the application that loads and runs them - in this case - Automator.  So, their capabilities should be governed by Automator's sandbox, which, due to the nature of Automator, should allow them to run unimpeded.

GUI Automation Tools for Mac OS X

I've received a lot of inquiries recently from people who are interested in controlling Mac OS X's GUI. First, let me say that there are some limitations inherent to most GUI automation processes. Here are the top five that I see most often...

  1. GUI automation is interface-reliant. It expects the interface to always be the same. If it changes, the process must be updated.
  2. GUI automation can sometimes be error prone. For example, changing the window layering on screen, accidentally clicking the mouse, and so forth, can cause some GUI automation tools to become confused.
  3. Tracking down the cause of a GUI automation error or problem is not always straightforward. Locating "button 12" of "window 500", for example, isn't as easy as it sounds.
  4. GUI automation tools typically have a limited ability to perform branching, i.e. looking at something, and making a decision about how to proceed.
  5. While GUI automation tools may be able to click around, select menus, and type keystrokes, they aren't good for "processing" actual data. For example, don't expect GUI automation to retrieve content from a database, bring it into an InDesign document, construct a catalog, output it to PDF, and send it to your printer.

For simple tasks, GUI automation may work just fine. For complex tasks, it may not. In these situations, you may need something much more robust, such as AppleScript, or AppleScript+GUI automation, or some other tool.

So, strictly with regard to GUI automation, there are a number of tools that can help you get the job done…

Automator - Automator has the ability to record manual tasks, and play them back as part of a workflow. Here are some resources I've released in the past to get you started…

Third-Party Automator Actions - My Automator Extension Action Pack includes several GUI automation actions, including:

  • Click Safari Web Form Button
  • Click Safari Web Form Checkbox
  • Click Safari Web Form Radio Button
  • Set Safari Web Form Text or Popup Field
  • Type Keystroke

Learn more or download a demo of my Automator actions here.

QuicKeys - An automation tool that can simulate user interaction by clicking buttons, selecting menus, and more. Essentially, a macro utility. Learn more on the QuicKeys website and in the following episode of my podcast...

iKey - Another macro utility for Mac OS X, allowing you to automate keystrokes, mouse clicks, and more. Learn more on the iKey website and in the following episode of my podcast...

Sikuli - An interesting visual automation tool for Mac OS X, which works from screenshots. Learn more on the Project Sikuli website.

Fake - A browser for automating web tasks, such as filling out forms, testing websites, and more. Learn more on the Fake.app website.

Eggplant - A visual, screen-shot-based automated testing tool, designed for automating processes across multiple machines (even PCs) through VPN. Learn more on the Eggplant website.

AppleScript Editor - Used to write AppleScripts, but also includes the ability to record manual tasks in certain applications as a script for later playback. Unfortunately, recordable applications are few and far between, but some include BBEdit, Fetch, and the Mac OS X Finder. Learn more in the following episode of my podcast...

If you are into AppleScript, check out my MacTech column on User Interface Scripting.