Home > Articles

  • Print
  • + Share This
This chapter is from the book

Mail Scripts

Mail is a highly scriptable application. It has to be because applications such as iCal rely on it to send notifications of events via AppleScript. The scripts in Mail Scripts demonstrate the ability to automatically create e-mail messages. Deep in the heart of most of them, you'll find some variation on these lines:

tell application "Mail"
 set theSubject to "Test Message"
 set theBody to "This is the message body."
 set theSender to "yourself@mac.com"
 set theRecipient to "jf@mac.com"
 set newMessage to make new outgoing message with properties ¬
  {subject:theSubject, content:theBody, sender:theSender, visible:true}
 tell newMessage
  make new to recipient at end of to recipients with properties¬
   {name:"Your Friend", address:"friend@mac.com"}
 end tell
 activate
end tell

NOTE

Lines of AppleScript code are terminated with the Return key. If the code requires more than one line, you can continue it on to a second line in Script Editor by using the AppleScript continuation character ¬, which is generated by the option-l key combination (that's the lowercase letter l, not the numeral 1). When you are using AppleScript Studio, Project Builder's formatting handles long lines for you; you simply keep typing and the text will wrap onto the next line. At the end of your AppleScript line of code (which may span several lines), press Return. In the examples in this book, continued lines are presented with the ¬ continuation character so that they can be pasted into Script Editor. In Part III, where AppleScript Studio projects are presented, the continuation character is not normally shown in the examples.

Although AppleScript syntax hasn't been described, you can probably pick out what's happening here. First, several variables (theSubject, theBody, and so forth) are set to strings. Then a new message is created, and it is instructed to add a recipient. The reason for this particular complication is that although a message can have only one subject, it can have many recipients, and the message needs to manage multiple recipients in a list.

There's another very brief script that uses a different method to create a message. In Quick Mail, the heart of the script is a single line:

open location "mailto:friend@mac.com?subject=Hello"

This is the same form of syntax that was used to open the AppleScript Web location. mailto is as valid an Internet prefix as is http, and so you can use the AppleScript open location command to create an e-mail message. The difference is that open location is an AppleScript command, and the previous example required you to use commands recognized by Mail.

Other Mail Scripts use the AppleScript syntax in Mail to report on the status of accounts and mailboxes. Most end by creating an e-mail message that displays the results.

  • + Share This
  • 🔖 Save To Your Account