Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

An AppleScript to batch-redirect email in Mail.app Apps
I've been trying to come up with a way to dump a bunch of email from a few of my email accounts to my new Gmail beta account. The problem is, I can't just forward the emails, because then the original headers (specifically the From address) get lost. Solution: the Redirect command. But Mail.app doesn't let you use Redirect on more than one email at a time! Hence, this AppleScript.

Obviously, replace firstname.lastname@gmail.com with the intended recipient of your redirected emails, and name with the full text of what you want to appear in the "Account" dropdown (i.e., the account that you want to use to send the redirected emails).
using terms from application "Mail"
  on perform mail action with messages selectedMessages
    set AppleScript's text item delimiters to ""
    set theRedirectRecipient to "firstname.lastname@gmail.com"
    set theRedirectSender to "name <name@fastmail.fm>"
    repeat with eachMessage in selectedMessages
      tell application "Mail"
        (* Uncomment this block and the "end if" below
        to ask if it's ok to forward each email
        set theSubject to the subject of eachMessage
        set theResult to display dialog "Redirect " & theSubject & ¬
        " to Gmail?" buttons {"OK", "Cancel"} default button 1
        if button returned of theResult is equal to "OK" then
        *)
        set theRedirectedEmail to redirect eachMessage ¬
          with opening window
        tell theRedirectedEmail
          make new to recipient at beginning of to recipients ¬
            with properties {address:theRedirectRecipient}
        end tell
        set the sender of theRedirectedEmail to theRedirectSender
        send theRedirectedEmail
        (* Also uncomment this block
        end if
        *)
      end tell
    end repeat
  end perform mail action with messages
end using terms from
That should do it. Save the AppleScript in your user's Library -> Scripts -> Mail Scripts folder, and you're good to go.
    •    
  • Currently 2.20 / 5
  You rated: 5 / 5 (5 votes cast)
 
[25,972 views]  

An AppleScript to batch-redirect email in Mail.app | 13 comments | Create New Account
Click here to return to the 'An AppleScript to batch-redirect email in Mail.app' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Remove "Modified by..." in subject?
Authored by: gwaldon on Apr 28, '04 01:17:33AM

Thanks for the script! I had been trying to write one of my own, but got stuck on a snag that you seem to have here also: the message subjects are appended with "Modified by [my name]". This doesn't happen when you simply redirect each message manually. Does anyone know a way around it? I've experimented with it a lot and I really can't tell where it's coming from, though it seems to happen in the step of adding the new recipient. (That is, if I have applescript just create the message, but I fill in the gmail address myself, then the subject doesn't get changed. However, if applescript both creates and addresses the message, and then I click send, the subject is modified, even though I can't see that in the window.)



[ Reply to This | # ]
Try formail(1) [was: Remove "Modified by..." in subject?]
Authored by: SlewSys on Apr 28, '04 06:04:39PM

The only command sufficiently powerful for redirecting mail that I am aware of is formail(1), which is part of the procmail(1) package. I believe it is native to OS X 10.3, at least.

Here is a sample command-line that I use for resending delivered mail.
Please read the manual carefully and proceed with caution, since the command must be executed as the super user (i.e., root).

# formail -s formail -k -X Subject: -R From: Reply-To: -X Reply-To: -s sendmail target-user@target.domain <mailbox

(all on one line) The second formail(1) command (i.e., formail -k ...) rewrites the `From:' header to `Reply-To:'. This way, if target-user wants to reply to a message, the reply will go to the original sender and not back to me. The first formail(1) command (i.e., formail -s ...) simply splits the mailbox up into individual messages.

Not exactly the answer you were looking for, but hopefully someone will find this useful...



[ Reply to This | # ]
Pleae help - getting the current subject etc in an open message
Authored by: peterpayne on Jan 14, '07 12:48:27AM

I've got an odd request. I need to be able to get the To:, Subject: and so on in the current open message, i.e. not a message that's been sent yet. I am having the devil's own time trying to figure out how I might do it, can anyone help? What I essentially need to do is make a duplicate of the current open message to the same recipient, but CC'ed to a separate address (a site where the user can read our mails if the spam filters eat the first message). If anyone can help me figure out how to get the current to, subject, content etc of the foremost open message window, I'd be forever in your debt.



[ Reply to This | # ]
An AppleScript to batch-redirect email in Mail.app
Authored by: Bubby Johnson on May 05, '04 06:24:33PM
Applescript does not cease to amaze me in its flexiblity, usefulness and unbelievable power even in the hands of the average user. Take for example this nice script, to batch redirect emails is really slick. I do have to mention one small, little caveat to this great script: When you redirect your mail every resent mail will HONOR the BCC tags. This may not be a problem for most, but if you are like me and the thought of resending age old emails around the globe inadvertently, then maybe you should try something else. I have experiemented with the above script and not quite found a satisfactory solution to the problem. I added two lines:

delete bcc recipients
delete cc recipients
But this takes me to the reason the solution is not quite satisfactory. It does not work if you reverse the order of the commands. If "delete cc" is first, I could not get the script to successfully remove the bcc tags. And even though there may be not be any CC tags, without this command the script wouldn't work. I think maybe a BCC tag is considered the same as a cc tag. So does the first swipe just remove the "B" and the second the "CC"? If anyone knows why it would be instructive. Here is my altered script in full:

using terms from application "Mail"
	on perform mail action with messages selectedMessages
		set AppleScript's text item delimiters to ""
		set theRedirectRecipient to "JohnSmith@something.com"
		set theRedirectSender to "John Smith <JohnSmith@something.com>"
		repeat with eachMessage in selectedMessages
			tell application "Mail"
				
				set theRedirectedEmail to redirect eachMessage with opening window
				tell theRedirectedEmail
					make new to recipient at beginning of to recipients with properties {address:theRedirectRecipient}
					delete bcc recipients
					delete cc recipients
				end tell
				set the sender of theRedirectedEmail to theRedirectSender
				send theRedirectedEmail
				
			end tell
		end repeat
	end perform mail action with messages
end using terms from
I removed the Dialog box that asked if it's OK to send. Refer to the first script to put it back in. Or just copy and paste the two lines from this script and put it in your own.

[ Reply to This | # ]
An AppleScript to batch-redirect email in Mail.app
Authored by: rlboydnc on Apr 06, '06 11:59:42AM

I tried using this script ... but when I try, it seems to do absolutely nothing.

I don't see anything in the log area. How can I find out what is happening/not happening?

Thanks!



[ Reply to This | # ]
An AppleScript to batch-redirect email in Mail.app
Authored by: zzztimbo on May 08, '06 01:56:41PM

i have the same exact problem. i'm running mail under 10.4.6.
can anyone help?



[ Reply to This | # ]
Forwarding Mail Script Problem
Authored by: brython on Feb 18, '05 04:58:33PM
Thanks for the great script! I'm actually looking for a way to forward my email to Earthlink's junkmail people (junkmail@earthlink.net). In order to do this, since it appeared that this script was pretty much what I was looking for, I just changed every instance of "Redirect" in the names of items to "Forward" (just for clarity), and got the following:
using terms from application "Mail"
	on perform mail action with messages selectedMessages
		set AppleScript's text item delimiters to ""
		set theForwardRecipient to "junkmail@earthlink.net"
		set theForwardSender to "myemail@earthlink.net"
		repeat with eachMessage in selectedMessages
			tell application "Mail"
				set theForwardedEmail to forward eachMessage ¬
					with opening window
				tell theForwardedEmail
					make new to recipient at beginning of to recipients ¬
						with properties {address:theForwardRecipient}
				end tell
				set the sender of theForwardedEmail to theForwardSender
				send theForwardedEmail
			end tell
		end repeat
	end perform mail action with messages
end using terms from
The problem is that somehow, the forwarded emails are being sent to ' '. Why is this happening? Am I missing something obvious here? (It's entirely possible, since I'm very new to AppleScript.) I appreciate any help! Greg

[ Reply to This | # ]
Simple solution without AppleScript
Authored by: ryangreenberg on May 20, '05 11:57:49AM

Having "Modified by..." appear in the subject of every redirected message is pretty annoying. Here's a simple solution to fix the problem and do it without AppleScript:

Create a new rule in Mail (Mail > Preferences... > Rules > Add Rule). Call it "Gmail Redirect" or something similar. Set the condition to "Every Message" and set the action to "Redirect Message." Enter your Gmail address in the provided box. Then click OK to save the rule. In Mail, select any messages you want to move to Gmail. Then go to Message > Apply Rules to re-apply all rules (including the redirect rule) to each message.

When I tried this in 10.3 Mail, this method preserved all sender information and dates with one caveat. The Gmail inbox shows the date the redirected messages were received (e.g. all the same time) but each individual message, when viewed, shows the original time it was sent.

I suppose you might run into problems if your ISP has limits on the amount of outgoing mail traffic, though.



[ Reply to This | # ]
Simple solution without AppleScript
Authored by: gxw on Jul 12, '05 10:30:33AM

Awsome tip. Thanks!

Saves me having to do all that cutting and pasting of text for those applescripts. <grin>.



[ Reply to This | # ]
reply, forward, and redirect AppleScript commands broken?
Authored by: morgant on Aug 06, '07 01:48:27PM

It appears that the reply, forward, and redirect AppleScript commands no longer return a reference to the outgoing message as their supposed to (see "Is redirect message broken?" on MacScripter).

How long has this been the case? Did this happen during the transition to Tiger because Apple now used the "message id" as the filename for the .emlx files (for improved Spotlight indexing) and so a new message no longer has a "message id"?



[ Reply to This | # ]
An AppleScript to batch-redirect email in Mail.app
Authored by: Stibble on Jun 02, '11 05:29:37AM

The batch re-direct using a 'new rule' works very well in Snow Leopard - I hadn't realised that the 'apply rules' only applied to selected emails so was nervous that everything would get sent - but now my gmail archive has just the ones I want !

Much simpler than scripting and now I can delete the rule for new email...



[ Reply to This | # ]
An AppleScript to batch-redirect email in Mail.app
Authored by: leonstafford on Sep 06, '11 02:59:14AM

I was also in the need for uploading about 175,000 emails into Gmail (upgraded to 80GB plan ;)

The scripts above no longer worked in Lion, so I mashed together a couple of scripts to get what I have been successfully using below.

I also added a utility to automatically add a set subject text for empty subject emails, else they would be waiting for user response to confirm sending emails with an empty title (annoying).

One thing also to be aware of is that you need a decent SMTP server for sending all these emails to Gmail with. Most providers, even MobileMe, have daily/hourly send limits, which are too small to be usable for such Gmail migration purposes.

I used an email account hosted on some MediaTemple, (dv) plan, web hosting, which has no daily send limits. This was the final key for me to get this all to work.

Any questions, please feel free to contact me.

OK, here is the code:

tell application "Mail"
	set AppleScript's text item delimiters to ""
	set theRedirectRecipient to "YOURGMAILADDRESSHERE@gmail.com"
	
	set theRedirectSender to "YOUR NAME HERE "
	
	
	set theMessages to the selection
	repeat with thisMessage in theMessages
		
		
		tell application "Mail"
			
			set theRedirectedEmail to redirect thisMessage with opening window
			tell theRedirectedEmail
				
				
				
				if subject of thisMessage is "" then
					
					set subject of theRedirectedEmail to "WAS EMPTY SUBJECT"
				end if
				
				
				
				make new to recipient at beginning of to recipients with properties {address:theRedirectRecipient}
				delete bcc recipients
				delete cc recipients
			end tell
			set the sender of theRedirectedEmail to theRedirectSender
			#delay 1
			send theRedirectedEmail
			
		end tell
		
	end repeat
end tell


[ Reply to This | # ]
An AppleScript to batch-redirect email in Mail.app
Authored by: ekepenne on Jan 08, '12 04:11:16AM
Hello everybody

Thanks for the tips regarding the forwarding/redirecting of emails.

I'm trying to forward specific incoming emails to my Evernote account. But before I forward the message, I wanted to add the date of the email and the desired Evernote-Notebook and Evernote-Tags to the subject. These added parameters are based on the name of the Mail rule.

Example:
- Initial subject is: This is the subject
- Email is dated: 7 January 2012
- Rule name is: @Notebook1 #Tag1 #Tag2

The new subject of the forwarded email will be:
This is the subject [7 January 2012] @Notebook1 #Tag1 #Tag2

In Evernote the message title will look like this: This is the subject [07.01.2012]
and the message will automatically be moved to Notebook1 and tagged with Tag1 and Tag2.

I used the code listed below and most of it works fine, but I have a strange issue.
The sender and subject are set correctly, but the message body and attachments are duplicated.
If I remove the line set subject of theRedirectedEmail to NewSubject, the message body and attachments is correct.
If I have 2 identical lines with this command set subject of theRedirectedEmail to NewSubject, the message body is tripled. It seems that I get a duplicated body/attachment for each "set" statement I add

Does anyone have any clue why I get this behavior?

Thank you ver much.
Regards, Eric

PS: My Mac runs OSX Lion 10.7.2.


on perform_mail_action(ruleData)
	
	-- Set parameters
	set AppleScript's text item delimiters to ""
	set theRedirectRecipient to "Evernote <MyEmailAddress@m.evernote.com>"
		
	-- Set the Notebook and tags of Evernote based on the name of the rule in Mail
	set NotebookTags to name of |Rule| of ruleData as text
	
	-- Get incoming messages that match the rule
	set selectedMessages to |SelectedMessages| of ruleData
	
	tell application "Mail"
		
		repeat with thisMessage in selectedMessages
			
			-- Get the date the message was sent
			set {year:y, month:m, day:d, hours:h, minutes:min} to thisMessage's date sent
			
			-- Prepare a date stamp " [dd.mm.yyyy] " for further use
			set dateStamp to (" [" & my pad(d) & "." & my pad(m as integer) & "." & y & "] ")
			set NewSubject to subject of thisMessage & dateStamp & NotebookTags
			
			set theRedirectedEmail to redirect thisMessage with opening window
			
			tell theRedirectedEmail
				make new to recipient at beginning of to recipients with properties {address:theRedirectRecipient}
				delete bcc recipients
				delete cc recipients
				set subject of theRedirectedEmail to NewSubject
			end tell
			
			send theRedirectedEmail
			
		end repeat
		
	end tell
	
end perform_mail_action

-- Adds leading zeros to date components
on pad(n)
	return text -2 thru -1 of ("00" & n)
end pad


[ Reply to This | # ]