Automatically download an attachment from link located in an email

Hi there, I’ve been dealing with this problem for a few months now and don’t seem to be able to get a solution. I receive a number of emails per day, from a specific sender. the emails contact some text and the word Download. The word Download contains a URL to a PDF. I would like an automated way to download the PDF.

What I have tried:
I have set up a rule in Apple Mail on MacOS with an AppleScript. The rule matches the correct emails and runs the applescipt. From an AppleScript perspective, most Applescripts I could find, are written o download an actual attachment contained in the email. I haven’t been able to tell AppleScript to look for the URL and then download the file that it points to. Is this even possible? I have also tried to save the raw email to disk but it either then drops the hidden urls from the words or the content is encoded and I cannot decode it correctly.

Is there a different way I can approach this? It’s driving me nuts.

1 Like

I did something similar to grab the login verification numbers that Microsoft send by email for some Office 365 instances.

My solution was a Mail rule to call an AppleScript. The script grabs the contents of the email then calls a Shortcut which uses Regex to identify the 8-digit number in the body of the email.

I imagine you could do something similar and use Shortcut’s Match action to find the URL in the text.

After that you’re on your own, but maybe this will move you a bit closer to a solution.

That sounds like a good start. Do you perhaps have that script around somewhere? Do you mind sharing it with me please?

No problem at all.

This script works but it relies on the assumption that the ‘right’ email is the first one in the inbox. If two emails came in at the same time, this might not be the case (and I’d love a way to pass a message from Mail, or even a definitive ID, but that’s not a problem I’ve solved).

tell application "Mail"
	set _msg to message 1 of inbox
	set _contents to content of _msg
end tell

tell application "Shortcuts Events" to run the shortcut named "MS Verification Code" with input _contents

The shortcut is very simple. The Match action finds the MS Code, it gets copied to the clipboard, then it pops a notification (so that you don’t have to keep checking for email).

I’d like to be able to do something similar to what you’re doing, saving an attachment from an email to Downloads (from where Hazel can process it), but that’s another as-yet unsolved problem.

Hope this helps.

Good news it looks like you should be able to do this with iOS 17 With a shortcut automation, that does not require any user action. Currently that shortcut cannot search the body of the email as a filter, so but it can trigger on a specific sender and subject.