3

This question follows on from the question: Drag messages from Mail onto Dock using Swift

I have now received a drag and drop message from dragging a message from Mail to the dock. The only thing that the I get is the message title and the message URL as follows:

message:%3C2004768713.4671@mail.stackoverflow.com%3E

How do I get the body text from this URL?

Thanks

Andrew

Community
  • 1
  • 1
iphaaw
  • 6,764
  • 11
  • 58
  • 83

1 Answers1

3

You can use a simple regular expression for this.

The .* parameter is hungry and will try to match as much as possible of the url subject:message pair before the (hopefully) last @ character in the string.

I have also included a small tool function (rangeFromNSRange()) to help convert an Objective-C NSRange struct into a proper Range<String.Index> Swift struct.

Paste the following in a Swift playground to see it working (and have fun!):

import Cocoa

func rangeFromNSRange(range: NSRange, string: String) -> Range<String.Index>
{
    let startIndex = string.startIndex.advancedBy(range.location)
    let endIndex = startIndex.advancedBy(range.length)
    return Range(start: startIndex, end: endIndex)
}

func parseEmailURL(urlAsString url: String) -> (subject: String, message: String)?
{
    let regexFormat = "^(.*):(.*)@"
    if let regex = try? NSRegularExpression(pattern: regexFormat, options: NSRegularExpressionOptions.CaseInsensitive)
    {
        let matches = regex.matchesInString(url, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, url.characters.count))

        if let match = matches.first
        {
            let subjectRange = rangeFromNSRange(match.rangeAtIndex(1), string: url)
            let messageRange = rangeFromNSRange(match.rangeAtIndex(2), string: url)

            let subject = url.substringWithRange(subjectRange)
            let message = url.substringWithRange(messageRange)

            return (subject, message)
        }
    }

    return nil
}

parseEmailURL(urlAsString: "message:2004768713.4671@mail.stackoverflow.com")
Bruno Philipe
  • 1,091
  • 11
  • 20
  • Thanks for your help, but this is not quite what I meant. I was wanting the text from the actual message not from the URL, which is a bit trickier. – iphaaw Oct 17 '15 at 05:22