Is It Possible to Inspect Webview of an Apple Mail Message with JXA?

I'm automating Apple Mail and need to somehow extract the HTML being rendered by Apple Mail's webkit. When I use various inspect tools all I get is the accessibility tree. Is it impossible to switch to webview context and extract the HTML elements? I've never used the Obj-c bridge but would that help?

Hey @Big_Rup,

Welcome to the forum!  :smile:

Unfortunately the answer to your question is no, however there are some possibilities.

This AppleScript will extract the source of the selected message in Mail:

# Auth: Christopher Stone
# dCre: 2020/11/10 14:48
# dMod: 2020/11/11 01:27
# Appl: Mail
# Task: Extract the Source of the Selected Message in Apple Mail
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @Mail, @Extract, @Source, @Selected, @Message

   tell application "Mail"
      set messageSelectionList to selection
      if messageSelectionList ≠ {} then
         set selectedMessage to item 1 of messageSelectionList
         tell selectedMessage
            set selectedMessageSource to its source
         end tell
         return selectedMessageSource
      end if
   end tell
on error e number n
   set e to e & return & return & "Num: " & n
   if n ≠ -128 then
         tell application (path to frontmost application as text) to set ddButton to button returned of ¬
            (display dialog e with title "ERROR!" buttons {"Copy Error Message", "Cancel", "OK"} ¬
               default button "OK" giving up after 30)
         if ddButton = "Copy Error Message" then set the clipboard to e
      end try
   end if
end try


Sadly this method can get really ugly when quoted-printable and other garbage is involved.

Run it in the Script to see the result. You'll get the full source including all the headers, and you'll have to parse out what you want.

If this works then great. If not let me know - I've got at least one other idea.


Thanks for the sugggestion will try asap