10.5: An AppleScript to link iCal events to Mail messages

Dec 19, '07 07:30:03AM

Contributed by: gaylward

I use mail and iCal at work, and often need to refer to agendas and other files which were sent by email. The new Message ID URL allows you to link to an email using the URL property of an iCal event. However, this involves displaying the header, copying and pasting.

The following AppleScript automates the process. Just select the email message, change to iCal, create or select the event, then run the script. You can then move the email out of your inbox and retrieve it later by a single click on the url link in the iCal event.

-- Script to read message id from selected mail message and put into iCal
-- Copyright 2007 G W Aylward

tell application "Mail"
  set selectedMessages to selection
  
  set selectionCount to (count of selectedMessages)
  
  -- Check that only one message is selected
  if selectionCount is greater than 1 then
    display dialog "Only one message should be selected"
  else if selectionCount is equal to 0 then
    display dialog "No messages selected"
  else
    set theMessage to item 1 of selectedMessages
    set messageid to message id of theMessage
    
    -- Make URL (must use URL-encoded values for "<" and ">")
    set urlText to "message://" & "%3c" & messageid & "%3e"
    
    -- Insert into currently selected event in iCal
    my insertURL(urlText)
  end if
  
end tell

-- Function to insert a URL into an iCal event (calendar choice hard-coded)
-- Uses system events as workaround for iCal bug (no selection property!)
on insertURL(urlText)
  tell application "iCal" to activate
  delay 1
  
  -- Get selected event summary into clipboard
  tell application "System Events"
    tell process "iCal"
      keystroke return
      keystroke "c" using {command down}
      keystroke return
    end tell
  end tell
  
  -- Now find event with that summary
  tell application "iCal"
    activate
    set myClipboard to the clipboard
    set myCal to calendar "Bill regular"
    set myEvent to first event of myCal whose summary is myClipboard
    
    -- Set URL and open event
    set url of myEvent to urlText
    show myEvent
    
  end tell
end insertURL
[robg adds: This worked as described when I tested it. To make it easy to run, save it to your user's Library/Scripts/iCal folder (create the folders as necessary).]

Comments (8)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20071208001422690