Using AppleScript to find specific text in mail message?

I'm new to scripting, and I'm a bit lost on this one...
Is there any way to use AppleScript to find a file name from within the body of a mail message so it can be used later in the script?
Specifically, I want to use AppleScript to "read" the content of a mail message and look for a paragraph that says "Filename: MyFileName" so I can set "MyFileName" as a variable. (There will always be a paragraph that begins with "Filename: " in this particular email message.)
This will part of a larger script that uses Fetch to download "MyFileName" from our FTP server.
Thanks in advance for any ideas - I'm struggling with this one.
Andy Gill

Ok, red_menace above me had a shorter and more elegant solution to the question, I'm adding this just for another example.
To solve your problem I'd make a mail rule that looked for any messages with "Filename:" in them (along with whatever criteria you wanted, like sender, domain, etc). The mail rule would execute the Applescript. My assumption is that the "Filename:foobar" text could be anywhere in the email, not necessarily the first thing in a paragraph, so I had to parse it differently.
The results end up in a datalist, (theFilename {} ) that you can parse later to collect all filenames found in whatever messages were processed.
I realize this could be cleaner, hope it's not hard to follow, but I did it really fast. It works flawlessly for me, picking out the name of the file no matter where in the email it appears.
using terms from application "Mail"
on perform mail action with messages theSelectedMessages for rule theRule
repeat with aCounter from 1 to count theSelectedMessages
set theMessage to item aCounter of theSelectedMessages
set theContent to content of theMessage
set theWords to every word of theContent
set theFilename to {}
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ":"
repeat with thisLoop in theWords
try
if (text item 1 of thisLoop) is "Filename" then
set end of theFilename to (text item 2 of thisLoop)
-- rest of your logic goes here the display is just to show it finds the filename, take it out!
display dialog theFilename ¬
buttons {"OK"}
end if
end try
end repeat
set AppleScript's text item delimiters to tid
end repeat
end perform mail action with messages
end using terms from
Message was edited by: stephen.bradley Typos for the win!

Similar Messages

  • Use REGEXP_INSTR to find a text string with space(s) in it

    I am trying to use REGEXP_INSTR to find a text string with space(s) in it.
    (This is in a Function.)
    Let's say ParmIn_Look_For has a value of 'black dog'. I want to see if
    ParmIn_Search_This_String has 'black dog' anywhere in it. But it gives an error
    Syntax error on command line.
    If ParmIn_Look_For is just 'black' or 'dog' it works fine.
    Is there some way to put single quotes/double quotes around ParmIn_Look_For so this will
    look for 'black dog' ??
    Also: If I want to use the option of ignoring white space, is the last parm
    'ix' 'i,x' or what ?
    SELECT
    REGEXP_INSTR(ParmIn_Search_This_String,
    '('||ParmIn_Look_For||')+', 1, 1, 0, 'i')
    INTO Position_Found_In_String
    FROM DUAL;
    Thanks, Wayne

    Maybe something like this ?
    test@ORA10G>
    test@ORA10G> with t as (
      2    select 1 as num, 'this sentence has a black dog in it' as str from dual union all
      3    select 2, 'this sentence does not' from dual union all
      4    select 3, 'yet another dog that is black' from dual union all
      5    select 4, 'yet another black dog' from dual union all
      6    select 5, 'black dogs everywhere...' from dual union all
      7    select 6, 'black dog running after me...' from dual union all
      8    select 7, 'i saw a black dog' from dual)
      9  --
    10  select num, str
    11  from t
    12  where regexp_like(str,'black dog');
           NUM STR
             1 this sentence has a black dog in it
             4 yet another black dog
             5 black dogs everywhere...
             6 black dog running after me...
             7 i saw a black dog
    5 rows selected.
    test@ORA10G>
    test@ORA10G>pratz
    Also, 'x' ignores whitespace characters. Link to doc:
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/conditions007.htm#i1048942
    Message was edited by:
    pratz

  • Since I have updated to ios 6 I cannot read the full text of mail messages

    Since I have updated to ios 6 I cannot read the full text of mail messages. With previous versions everything worked fine. The only way to read the full text is to answer the mail. Thank you for your help. Regards.

    Close out of the mail app.  Double tap the home button, find the mail app hold down until you see the red minus sign and hit that.   then go back into the mail app and open an email you should now be able to read the full content of the email.

  • Applescript get text from mail message

    Hi,
    I've got a nested script that ideally would work with a multiple selection of emails. Most of the script does but I've recently found the need to add the sender's delivery address to the outgoing message. I've found a way to insert the clipboard but that leaves me only being able to send out one message at a time and I have to copy the address for each message to the clipboard first. I made a script to do that bit once I'd selected the text but this only works from Applescript Editor and not Quicksilver which is what I normally use.
    So, what I'm hoping is someone would be able to help me with the a, select the right bit of text between Delivery address: and Instructions to merchant: of each message and have that work with Quicksilver and b, tell me why the following script only partially works from Quicksilver, i.e. the top bit, copy to clipboard, doesn't work.
    Thanks.
    tell application "System Events"
      tell application "Mail" to activate
      key code 8 using command down
    end tell
    tell application "Mail"
      set thesenders to {}
      set thesenderstext to ""
      set myaddress to the clipboard
      set theMessages to the selection
      repeat with eachMessage in the theMessages
      repeat with i from 1 to the number of items in eachMessage
      set theAccount to "[email protected]"
      set theSender to (extract address from (the reply to of (item i of eachMessage)))
      if thesenders does not contain theSender then
      set thesenders to {theSender}
      end if
      set replyName to (extract name from (the sender of (item i of eachMessage)))
      set titleCaseString to (do shell script "/bin/echo" & space & quoted form of replyName & space & "| /usr/bin/perl -p -e 's/(\\w+)/\\u\\L$1/g;'") as Unicode text
      set firstName to word 1 of titleCaseString
      end repeat
      set AppleScript's text item delimiters to ", "
      set thesenderstext to thesenders as rich text
      set AppleScript's text item delimiters to ""
      set newMessage to make new outgoing message
      set theSubject to "instructions"
      set theContent to "Dear " & firstName & ",
    Thanks so much for your order.
    You will receive a despatch notice by email when your order is sent.
    Your  Order is being sent to:
    " & myaddress & "
    Kind Regards
    Jim
      set newMessage to make new outgoing message with properties {subject:theSubject, content:theContent, visible:true}
      set theAttachment1 to POSIX file "/Users/Jim/qrcode.13177607.png"
      set theAttachment2 to POSIX file "/Users/Jim/qrcode.13177658.png"
      set theAttachment3 to POSIX file "/Users/Jim/qrcode.13177665.png"
      tell newMessage
      set visible to true
      make new to recipient with properties {address:thesenderstext}
      --make new bcc recipient at end with properties {address:theBccRecipient}
      make new attachment with properties {file name:theAttachment1} at after the last paragraph
      make new attachment with properties {file name:theAttachment2} at after the last paragraph
      make new attachment with properties {file name:theAttachment3} at after the last paragraph
      -- send
      end tell
      tell application "Mail"
      set a to selection
      repeat with s in a
      set flag index of s to -1 as integer
      end repeat
      set theSelection to the selection
      repeat with theMessage in the theSelection
      move theMessage to mailbox "orders" -- of account theAccount
      activate
      end repeat
      end tell
      end repeat
      set read status of every message of mailbox "orders" to true
    end tell

    Shoot! I wrote this huge reply and then quit Safari by accident. I'm too tired to type it all over again (I should install a keylogger).
    Anyway, check out the screen shot of my workflow. the AppleScript section is where it xfers the URL from a text editor (BBEdit) to Safari. It's pretty dirty but it works.
    http://www.jameskocsis.com/urlworkflow.jpg
    post antother reply if you need more data on this process.
    Good luck.
    -James

  • Editing text in Mail message act very strange since Mavericks

    Hi,
    i've updated to mavericks but since then when i'm editing text in Mail my cursor is placing the typed text in another part of sentence. Very annoying and frustrating. Anyone?

    Please read this whole message before doing anything.
    This procedure is a diagnostic test. It’s unlikely to solve your problem. Don’t be disappointed when you find that nothing has changed after you complete it.
    The purpose of the test is to determine whether the problem is caused by third-party software that loads automatically at startup or login, by a peripheral device, by a font conflict, or by corruption of the file system or of certain system caches.
    Disconnect all wired peripherals except those needed for the test, and remove all aftermarket expansion cards, if applicable. Start up in safe mode and log in to the account with the problem. You must hold down the shift key twice: once when you boot, and again when you log in.
    Note: If FileVault is enabled, or if a firmware password is set, or if the boot volume is a Fusion Drive or a software RAID, you can’t do this. Ask for further instructions.
    Safe mode is much slower to boot and run than normal, with limited graphics performance, and some things won’t work at all, including sound output and Wi-Fi on certain models. The next normal boot may also be somewhat slow.
    The login screen appears even if you usually login automatically. You must know your login password in order to log in. If you’ve forgotten the password, you will need to reset it before you begin.
    Test while in safe mode. Same problem?
    After testing, reboot as usual (not in safe mode) and verify that you still have the problem. Post the results of the test.

  • Group Contact Setup for Text & E-mail Messaging

    It would appear that compared to my previous BB Bold my new Z10 is unable to create group contacts for both Text and E-Mail messaging. Will this be addressed by RIM or is there an App available?

    You should be abel to go to the O2 website and select to have the O2 connection settings sent to your phone via sms.
    Try this web page.
    http://getsettings.o2.co.uk/ServeSettingsWebApp/
    N97 (Product Code: 0585262 (Voda UK)) FW 12.0.026
    95 8Gb (Product Code: 0558787 (UK)) FW 31.0.018
    If a post by a user has been helpful, please click on the Kudos! button.

  • How do I format the text in mail messages?

    I receive some mail messages that extend well beyond the screen and I have to scroll a long ways to finish reading one line. Is there any way to format the mail to automatically fold these long lines so that  i can read them without so much scrolling?
    Thanks for any help.

    Copy paste the content of the message to Textwrangler from http://www.barebones.com/
    Then use its word-wrap options.

  • Using AppleScript to find and move text within a TextEdit document.

    The goal is to do massive restructuring of data within a text edit file that requires a great deal of repetative operations using find text. The process is to use find to locate the item, exit Find at the location in which the item resides, go to the beginning of the line, select the whole line, cut, use find to relocate to the new location, exit Find at the new location, go to the beginning of the line, and paste repeating the process until all the data is restructured. The only problem is that I cannot exit Find using the "Done" button which would put the cursor at the right spot to begin the move. Searching the internet, I found:
         click button "Done" in scroll area 1
    however, that results in:
         error "System Events got an error: Can’t get scroll area 1." number -1728 from scroll area 1
    Searching the internet has not turned up any other method. Anyone that can help?

    You can use find, something like:
    find /dir -name "*.jpg" -exec mv {} dirnew/ \;
    man find for the details...

  • Use Applescript to find files with certain conditions

    I am using a tool to batch convert audio files in APE format to MP3. I have thousands of files located in hundreds of folders and subfolders in my hard drive so I searched for all APE/FLAC files and then dragged and dropped them in the tool for conversion. The problem is I was not able to convert all the files successfully for a variety of reasons (original APE files are corrupt, etc.), as a result I was left with a situation where some of the folders have files convernted (both APE and MP3 in that folder) whereas others don't (APE only). Instead of manually go to each folder and subfolder to find which ones need me to convert is there an Applescript I can use to quickly list the APE files that have not been converted?

    Hello
    You may try the following shell script. Please specify DIR as the root directory to start searching. It will create output list named no_mp3_list.txt on desktop.
    #!/bin/bash
    #     list every *.ape file which has no corresponding *.mp3 file in the same directory
    #     * name matching is done in case-insensitive fashion
    DIR=~/Desktop/test                # root directory to start scanning
    OUT=~/Desktop/no_mp3_list.txt    # output file
    shopt -s nocasematch
    while read -d $'\0' f
    do
        [[ -e "${f:0:${#f}-3}mp3" ]] || echo "$f" >> "$OUT"
    done < <(find "$DIR" -iname '*.ape' -print0)
    And in case, here's a simple AppleScript wrapper for the above, which lets you choose the root directory.
    set f to (choose folder with prompt "choose root folder to start searching")'s POSIX path
    if f ends with "/" then set f to f's text 1 thru -2
    do shell script "/bin/bash -s <<'EOF' -- " & f's quoted form & "
    #     list every *.ape file which has no corresponding *.mp3 file in the same directory
    #     * name matching is done in case-insensitive fashion
    DIR=\"$1\"                        # root directory to start searching
    OUT=~/Desktop/no_mp3_list.txt    # output file
    shopt -s nocasematch
    while read -d $'\\0' f
    do
        [[ -e \"${f:0:${#f}-3}mp3\" ]] || echo \"$f\" >> \"$OUT\"
    done < <(find \"$DIR\" -iname '*.ape' -print0)
    EOF"
    Hope this may help,
    H

  • How to find specific text WITHIN iTunes lyrics?

    I've been trying to figure out how to search within existing iTunes song lyrics for specific words or phrases, for the purpose of making specific playlists of all songs that contain the specified text.
    As an example, I'd like to find all the songs (out of a couple thousand or so) that contain the word "Instrumental" and place them in a list.  Perhaps from there, I'd change all of those songs' Comments to show "[Instrumental]" or some such to make it easier to use some of iTunes built-in tools, or your own excellent ones.
    Or maybe I could look for songs that have the word "Notice" in them, so I can examine their lyrics to spot those which only had partial lyrics auto-loaded to them, so I could do a more thorough manual search.
    Thanks,
      Ed

    I think I'm on the good way with this:
        app.findTextPreferences = NothingEnum.nothing;
        app.changeTextPreferences = NothingEnum.nothing;
        app.findTextPreferences.findWhat = "CAR67765756";
        app.changeTextPreferences.changeTo = "bhbdbds"
        found = app.activeDocument.findText (true);
        if(found.length>0)
            for (j = 0; j < found.length; j++)
                found[j].select();
                alert("true");
                app.documents.item(0).changeText();   
        else
            alert("false");
        app.findGrepPreferences = app.changeGrepPreferences = null;
        app.changeGrepPreferences = app.changeGrepPreferences = null;

  • Using Applescript to find QT Properties

    I'm looking for the syntax for applescript to be able to read the video & audio format of a QT movie. What I need to do is find out what the codecs the movie is using so then I can use another part of the script to either recompress the movie or upload should it be in the correct format.
    I'd also love to know a way of finding out what codec is used without having to open QT Player. I know I can use the spotlight index (command line mdls) for this but we have spotlight disabled in my labs.
    Thanks for any tips!

    is this a separate script or a Mail rule?  at any rate, all you need to so is use the test phrase 'subject contains "ordering prepare"', though how you apply that differs according to how the script is structured.

  • Using applescript for Find and Replace All in Pages 2.0

    i saw that Pages 2.0 is scriptable
    i try to create a script for merge use to find and replace all occurence of a certain string using a script but Pages doesn't seems to respond to "Find" even using "System Events"
    how can i do to use this function with a script
    Thanx for any help
    S.B.
    ibook G3   Mac OS X (10.4.6)  

    OK, here's another example. This one gets the text as a string and uses the offset property to find "[", presuming it to be a merge delimiter. (Pages' text doesn't support "offset of").
    One failing of this scheme is that the offsets are incorrect if you have inline objects (pictures, shapes, tables, etc.). While it is probably possible to compensate for them, that's a trickier proposition.
    <PRE>-- Example merge replacements:
    property mergeText : {"[name]", "John Smith", "[address]", "1234 Anystreet"}
    on lookup(mergeWord)
    set theCount to count of mergeText
    repeat with x from 1 to theCount by 2
    if item x of mergeText = mergeWord then
    return item (x + 1) of mergeText
    end if
    end repeat
    -- If merge field is not found, delete it (replace it with the empty string)
    return ""
    end lookup
    tell application "Pages"
    repeat
    tell body text of document 1
    -- Get text as a string so that "offset of" can be used.
    set allText to it as string
    set startOffset to offset of "[" in allText
    if (startOffset = 0) then
    exit repeat
    end if
    set endOffset to offset of "]" in allText
    select (text from character startOffset to character endOffset)
    end tell
    set mergeWord to contents of selection
    tell me to lookup(mergeWord)
    set replacement to result
    set selection to replacement
    if (replacement is "") then
    -- Get rid of extra whitespace (space or return)
    -- Do it in a "try" block to handle edge cases at start or end of text.
    try
    set theSel to (get selection)
    set ch1 to character before theSel
    set ch2 to character after theSel
    if ((ch1 is " " or ch1 is return) and (ch2 is " " or ch2 is return)) then
    select character after theSel
    delete selection
    end if
    end try
    end if
    end repeat
    end tell</PRE>
    Titanium PowerBook   Mac OS X (10.4.6)  

  • Using AppleScript to create a text file, based on an OCR'd file's content

    Hey guys, I've got an interesting situation.
    I was wondering if there would be anyway to use something like AppleScript (or the like) to create a text document and fill it with information based on what is found in an already OCR'd file?
    For example: I have a paycheck stub. The stub contains the words "Gross Pay" and the value "$xxxx.xx" on one line. Using Hazel to identify paychecks (based upon filenames), could I then use something like AppleScript, to create a new text file, and then pull the text from the line that contains the word's "Gross Pay" and insert it into the text file's next line?
    Ex:
    March 26,2012      
    Gross Pay                   $xxxx.xx
    April 6,2012
    Gross Pay                   $xxxx.xx
    Kind of how TurboTax's iPhone app pulls text from an image, then uses the values to insert it into the app's appropriate fields?
    I know this may be a lot to ask, but any help is appreciated. Thanks!

    StevenD: FYI, I did NOT give you the one star rating. I would never do that!
    StevenD wrote:
    Ow. Someone is grumpy today.
    Well, this is an assignment, so it is probably homework.
    Why else would anyone give HIM such an assigment, after all he has no LabVIEW experience and the tutorials are too hard for him?
    This would make no sense unless all of it was just covered in class!
    This is not a free homework service with instant gratification.
    OK! Let's do it step by step. I assume you already have a VI with the digital indicators.
    "...but have no idea where to begin".
    open notepad.
    decide on a format, possibly one line per indicator.
    type the document.
    close notepad.
    open LabVIEW.
    Open the existing VI with all the indicators.
    (are you still following?)
    look at the diagram.
    Who made the program?
    Does the code make sense so far?
    Is it a statemachine or just a bunch of crisscrossed wires?
    Where do you want to add the file read?
    How should the file be read (after pressing a read button, at the start of the program ,etc.)
    See how far you get!
    Message Edited by altenbach on 06-24-2008 11:23 AM
    LabVIEW Champion . Do more with less code and in less time .

  • How to use automator to extract specific text from json txt file

    I'm trying to set up an Automator folder action to extract certain data from json files. I'm pulling metadata from YouTube videos, and I want to extract the Title of the video, the URL for the video, and the date uploaded.
    Sample json data excerpts:
    "upload_date": "20130319"
    "title": "[title of varying length]"
    "webpage_url": "https://www.youtube.com/watch?v=[video id]"
    Based on this thread, seems I should be able to have Automator (or any means of using a shell script) find data and extract it into a .txt file, which I can then open as a space delimited file in Excel or Numbers. That answer assumes a static number of digits for the text to be extracted, though. Is there a way Automator can search through the json file and extract the text - however long - after "title" and "webpage_url"?
    json files are all in the same folder, and all end in .info.json.
    Any help greatly appreciated!

    Hello
    You might try the following perl script, which will process every *.json file in current directory and yield out.csv.
    * CSV currently uses space for field separator as you requested. Note that Numbers.app cannot import such CSV file correctly.
    #!/bin/bash
    /usr/bin/perl -CSDA -w <<'EOF' - *.json > out.csv
    use strict;
    use JSON::Syck;
    $JSON::Syck::ImplicitUnicode = 1;
    # json node paths to extract
    my @paths = ('/upload_date', '/title', '/webpage_url');
    for (@ARGV) {
        my $json;
        open(IN, "<", $_) or die "$!";
            local $/;
            $json = <IN>;
        close IN;
        my $data = JSON::Syck::Load($json) or next;
        my @values = map { &json_node_at_path($data, $_) } @paths;
            #   output CSV spec
            #   - field separator = SPACE
            #   - record separator = LF
            #   - every field is quoted
            local $, = qq( );
            local $\ = qq(\n);
            print map { s/"/""/og; q(").$_.q("); } @values;
    sub json_node_at_path ($$) {
        #   $ : (reference) json object
        #   $ : (string) node path
        #   E.g. Given node path = '/abc/0/def', it returns either
        #       $obj->{'abc'}->[0]->{'def'}   if $obj->{'abc'} is ARRAY; or
        #       $obj->{'abc'}->{'0'}->{'def'} if $obj->{'abc'} is HASH.
        my ($obj, $path) = @_; 
        my $r = $obj;
        for ( map { /(^.+$)/ } split /\//, $path ) {
            if ( /^[0-9]+$/ && ref($r) eq 'ARRAY' ) {
                $r = $r->[$_];
            else {
                $r = $r->{$_};
        return $r;
    EOF
    For Automator workflow, you may use Run Shell Script action as follows, which will receive json files and yield out_YYYY-MM-DD_HHMMSS.csv on desktop.
    Run Shell Script action
        - Shell = /bin/bash
        - Pass input = as arguments
        - Code = as follows
    #!/bin/bash
    /usr/bin/perl -CSDA -w <<'EOF' - "$@" > ~/Desktop/out_"$(date '+%F_%H%M%S')".csv
    use strict;
    use JSON::Syck;
    $JSON::Syck::ImplicitUnicode = 1;
    # json node paths to extract
    my @paths = ('/upload_date', '/title', '/webpage_url');
    for (@ARGV) {
        my $json;
        open(IN, "<", $_) or die "$!";
            local $/;
            $json = <IN>;
        close IN;
        my $data = JSON::Syck::Load($json) or next;
        my @values = map { &json_node_at_path($data, $_) } @paths;
            #   output CSV spec
            #   - field separator = SPACE
            #   - record separator = LF
            #   - every field is quoted
            local $, = qq( );
            local $\ = qq(\n);
            print map { s/"/""/og; q(").$_.q("); } @values;
    sub json_node_at_path ($$) {
        #   $ : (reference) json object
        #   $ : (string) node path
        #   E.g. Given node path = '/abc/0/def', it returns either
        #       $obj->{'abc'}->[0]->{'def'}   if $obj->{'abc'} is ARRAY; or
        #       $obj->{'abc'}->{'0'}->{'def'} if $obj->{'abc'} is HASH.
        my ($obj, $path) = @_; 
        my $r = $obj;
        for ( map { /(^.+$)/ } split /\//, $path ) {
            if ( /^[0-9]+$/ && ref($r) eq 'ARRAY' ) {
                $r = $r->[$_];
            else {
                $r = $r->{$_};
        return $r;
    EOF
    Tested under OS X 10.6.8.
    Hope this may help,
    H

  • Find & replace in HTML mail message to change color

    I have a script someone wrote for me to automatically print my school's attendance list when it comes into my inbox. I have a very limited understanding of AppleScript, but it seems to clean up the message and then send it to print. The one thing I would like to change is the color of the banner at the top of the page which is blue (coded cyan in the html) since it keeps using up all of the blue ink in my printer before the other colors. I am pasting the script below. How can I include some lines that will change cyan to gray or even white?
    Anthony
    on performmailaction(info)
    tell application "Mail"
    set selectedMessages to |SelectedMessages| of info
    repeat with eachMsg in selectedMessages
    set theSource to source of eachMsg as text
    set AppleScript's text item delimiters to (ASCII character 10) & (ASCII character 10)
    set theSource to text items 2 thru -1 of theSource as text
    set AppleScript's text item delimiters to "=" & (ASCII character 10)
    set theSourceItems to text items of theSource
    set AppleScript's text item delimiters to ""
    set theSource to theSourceItems as text
    set AppleScript's text item delimiters to "=3D"
    set theSourceItems to text items of theSource
    set AppleScript's text item delimiters to "="
    set theSource to theSourceItems as text
    set AppleScript's text item delimiters to "=20"
    set theSourceItems to text items of theSource
    set AppleScript's text item delimiters to " "
    set theSource to theSourceItems as text
    set AppleScript's text item delimiters to "</HTML>"
    set theSource to text item 1 of theSource as text
    set AppleScript's text item delimiters to "<PRE>"
    set theSourceItems to text items of theSource
    set AppleScript's text item delimiters to ""
    set theSource to theSourceItems as text
    set AppleScript's text item delimiters to "</PRE>"
    set theSourceItems to text items of theSource
    set AppleScript's text item delimiters to ""
    set theSource to theSourceItems as text
    set theFile to open for access (((path to desktop folder) as text) & "Mail_tmp.html") with write permission
    set eof of theFile to 0
    write theSource & "</HTML>" to theFile starting at eof
    close access (((path to desktop folder) as text) & "Mail_tmp.html") as file specification
    tell application "Finder"
    print alias (((path to desktop folder) as text) & "Mail_tmp.html")
    delete alias (((path to desktop folder) as text) & "Mail_tmp.html")
    end tell
    end repeat
    tell application "TextEdit"
    quit
    end tell
    end tell
    end performmailaction

    Hello
    As my goal is only to check that what I wrote runs correctly, I commented all your code which is not of "my responsability".
    I ran the "stripped code" and got exactly what was wished: the words "Date:" and "Subject:" are in bold while all the remaining text is in plain .
    At this time I am unable to apply Times to the plain text.
    You may check the "stripped script" and when you will be convinced that this piece of code does its duty, you will have to search what is the wrongdoer in your own code.
    -- [SCRIPT]
    tell application "Mail"
    activate
    set selectedMessages to the selected messages of front message viewer
    set saveFolder to choose folder with prompt "Please pick an empty folder for me to store the manuscript information:"
    tell application "Finder"
    set parentFolder to folder saveFolder
    set parentFolderPath to parentFolder as Unicode text
    end tell -- to Finder
    repeat with aMessage in selectedMessages
    properties of aMessage
    set messageSender to sender of aMessage
    set messageSubject to subject of aMessage
    set messageSent to date sent of aMessage as string
    set messageContent to content of aMessage
    if (messageSender is "[email protected]") and (messageSubject begins with "manuscript #") then
    -- Get manuscript number from message subject after '#'
    set oldDelimiter to my SwitchDelimiterTo({"#"})
    set manuscriptNumber to last text item of messageSubject
    my SwitchDelimiterTo(oldDelimiter)
    log "NOTE: Email for manuscript #" & manuscriptNumber
    -- Make the folder in which to store the stuff for this manuscript;
    -- variable "manuscriptFolder" will point to place to store files
    tell application "Finder"
    try --ignore problems with folder creation, like existing folders/files
    set manuscriptFolder to make new folder in parentFolder with properties {name:manuscriptNumber}
    on error errorName number errorNumber
    if errorNumber is -48 then -- Folder already exists
    log "NOTE: folder " & parentFolderPath & manuscriptNumber & " already exists."
    set manuscriptFolder to folder manuscriptNumber in parentFolder
    end if
    end try
    end tell -- to Finder
    set manuscriptFolderPath to manuscriptFolder as Unicode text
    set messageFileName to manuscriptFolderPath & "email.rtf"
    log "NOTE: Saving manuscript to file: " & messageFileName
    -- Use TextEdit to construct an RTF file of the message to print out later
    set messageSent to "mardi 13 mars 2007"
    set messageSubject to "sujet du message"
    set messageContent to "blablabla…"
    tell application "TextEdit"
    activate
    close every document saving no
    set aDocument to make new document at beginning of documents
    set fontReg to "Courier New"
    set fontBold to "Courier New Bold"
    set font of aDocument to fontReg
    -- Assemble the document using the clipboard and pasting
    -- Stick in "Date:"
    set the clipboard to "Date:"
    my triggerCmdKey("v", "TextEdit") -- Cmd-v, paste
    set font of last word of document 1 to fontBold
    -- Stick in date string
    set the clipboard to tab & tab & messageSent & return
    my triggerCmdKey("v", "TextEdit") -- Cmd-v, paste
    -- Stick in "Subject:" and boldify it
    set the clipboard to "Subject:"
    my triggerCmdKey("v", "TextEdit") -- Cmd-v, paste
    delay 1
    set font of last word of document 1 to fontBold
    -- Stick in the subject
    set the clipboard to tab & messageSubject & return & return
    my triggerCmdKey("v", "TextEdit") -- Cmd-v, paste
    -- Stick in the message content
    set the clipboard to messageContent & return
    my triggerCmdKey("v", "TextEdit") -- Cmd-v, paste
    -- Save the document as an RTF in the messageFileName
    tell front document
    save in messageFileName
    end tell -- to front document
    end tell -- to TextEdit
    else
    log "Message from \"" & messageSender & "\" with subject \"" & messageSubject & "\" will not be processed."
    end if
    end repeat
    end tell -- to Mail
    -- Change the text item delimiter and return the existing ones
    on SwitchDelimiterTo(delimiterList)
    local x
    set x to (get AppleScript's text item delimiters)
    set AppleScript's text item delimiters to delimiterList
    return x
    end SwitchDelimiterTo
    -- Trigger a System Event for a Command-<key> in the named application
    on triggerCmdKey(k, appName)
    tell application appName to activate
    tell application "System Events" to tell application process appName to keystroke k using {command down}
    end triggerCmdKey
    --[/SCRIPT]
    Yvan KOENIG (from FRANCE jeudi 15 mars 2007 21:09:53)

Maybe you are looking for