Hi, community.
Does someone know whether it’s possible to obtain RTF data from a specific mail message using asobjc
?
Mail scripting dictionary contains the following property:
content: rich text
However, I didn’t have luck obtaining rich text data.
Perhaps the clipboard provides a feasible route ?
Once you have selected and copied some part (or all) of the message content, you can then read the public.rtf
pasteboard item.
1 Like
That worked. Thank you very much Rob.
Of course, I would have hoped for a solution which doesn’t involve selecting the message. content
property seemed promising. But this is very good.
1 Like
You can also load an attributed string from the HTML source of the message, e.g.:
use framework "AppKit"
tell application "Mail"
-- Get the message (using selection here, but could get by ID all the same)
set theMessage to item 1 of (selection as list)
-- Get the source HTML as an NSString object
set theSourceString to current application's NSString's alloc()'s initWithString:(source of theMessage)
-- Create an attributed string from the HTML data
set theHTMLData to theSourceString's dataUsingEncoding:(current application's NSUnicodeStringEncoding)
set attributedString to current application's NSAttributedString's alloc()'s initWithHTML: theHTMLData documentAttributes:(current application's NSDictionary's alloc()'s init())
-- Load the data as RTF & save to file
set theRTFData to attributedString's RTFFromRange:{0, attributedString's |length|()} documentAttributes:(current application's NSDictionary's alloc()'s init())
theRTFData's writeToFile:"/Users/example/Downloads/example.rtf" atomically:false
end tell
You might want to mess around with the range a bit to isolate just the content of the message, excluding headers.
2 Likes
Thank you so much, Stephen. I’ll try and report back when I am back at the computer.
Hello, Stephen.
Just back from a trip and tested.
I get:
2023-08-15 09:58:28.157 osascript[1891:77816] *** -[NSConcreteAttributedString initWithHTML:documentAttributes:]: value passed to argument of type ^@ must be either missing value' or
reference’; assuming `missing value’.
false
Any ideas about this error ?
Hm, that error only shows when I run it via osascript, but it still creates the RTF file correctly and returns true.
To remove the error: try changing the attributedString line to this: set attributedString to current application's NSAttributedString's alloc()'s initWithHTML:theHTMLData documentAttributes:(missing value)
Also make sure you replace ‘example’ in the output file path at the end with your user.
1 Like