Friday, May 29, 2020

#1 2015-03-29 05:40:49 pm

kurttodoroff
Member
Registered: 2008-05-24
Posts: 42

Save Apple Mail And Attachments As PDF

I posted this, seven years ago.  Perhaps, several new OS X versions later, this is possible.

I am requesting assistance with a Mail issue.  I am searching for an Applescript that:

1:  Prompts and allows the user to select one or more Apple Mail email messages from within Mail.

2:  Prompts and allows the user to select a save-to folder.

3:  For each message, saves it as a PDF file in the save-to folder, using the following naming convention for the PDF file:

     "YYYY-MM-DD HH.MM.SS Email From FIRSTNAME LASTNAME - SUBJECT",

     "YYYY-MM-DD HH.MM.SS Email To FIRSTNAME LASTNAME - SUBJECT",

where, in the email date-sent stamp (if I am the sender), or, in the date-received stamp (if I am the recipient):

YYYY = the year
MM = the two-digit month
DD = the two-digit day
HH = the two-digit hour (in 24-hour time)
MM = the two-digit minute
SS = the two-digit second
FIRSTNAME is the email sender's first name for email that I receive (or is the email recipient's first name for email that I send)
LASTNAME is the email sender's last name for email that I receive (or is the email recipient's first name for email that I send)
SUBJECT = the email's subject line

For example:  2015-01-11 16.32.48 Email From Jill Nicole - Status Of Payroll Updates.pdf
For example:  2015-01-11 16.33.55 Email To Carol Davis - RE Status Of Payroll Updates.pdf  (Colon omitted after "RE".)

4:  For each attachment to the message, saves it as a PDF file in the same directory using the naming convention:

     "YYYY-MM-DD HH.MM.SS Email From FIRSTNAME LASTNAME Z Attachment - NUMBER - FILENAME",

where:

YYYY-MM-DD HH.MM.SS Email From FIRSTNAME LASTNAME = as above
NUMBER = an integer representing the attachment number (1, 2, ...) sorted according to filename alphabetical order
FILENAME = the name of the file attached to the email, including its extension (.docx, .xlsx, etc.)
The letter "Z" sorts the attachment PDFs after its respective parent email in the directory.

For example:  2015-01-11 16.32.48 Email From Jill Nicole Z Attachment - 1 - List Of Suggestions To Moore.doc.pdf
For example:  2015-01-11 16.32.48 Email From Jill Nicole Z Attachment - 2 - Proposed Salary Adjustments.xls.pdf
For example:  2015-01-11 16.32.48 Email From Jill Nicole Z Attachment - 3 - Salary History.pps.pdf


Note: Approximately two-thirds of all of the emails will have no attachments. The remainder will have one or more attachments consisting of a PDF or MS Office file (Word, Excel, Power Point); however, a smart implementation will be able to handle any attachment kind.  If the attachment is a PDF file, then save it "as is" using the stipulated naming convention.

Thank you for any and all assistance.

Kurt

Offline

 

#2 2015-03-30 07:03:50 am

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 4370

Re: Save Apple Mail And Attachments As PDF

You may try to run :

Applescript:

(*
# Define the folder where files will be stored
set storageName to "Attachments"
set p2d to path to documents folder from user domain
set attachmentsFolder to (p2d as text) & storageName & ":"
do shell script "/bin/mkdir -p " & quoted form of (POSIX path of attachmentsFolder)
*)

# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
# OF COURSE YOU MAY USE: set attachmentsFolder to ( choose folder) as text
set attachmentsFolder to (choose folder) as text
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=

# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
set mySelf to {"Kurt YourLastName", "YourLastName Kurt"} # I USE BOTH FORMATS, EDIT TO FIT YOUR NEEDS
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=

tell application "Mail"
   activate
   set theMessages to (get selection)
end tell

---------------------------------------
repeat with eachMessage in theMessages
   --Open an mail and treat it
   tell application "Mail"
       open eachMessage
       delay 0.5
       set wName to name of window 1
       
       tell eachMessage # extracts datas from the selected message
           set sender_Name to extract name from its sender
           set sender_Mail to extract address from its sender
           set mail_Subject to subject
           set mail_Date to date received # will keep the time component
           set target_name to (name of its to recipient)
       end tell # the message
   end tell # Mail
   
   # No longer speak to Mail
   
   tell mail_Date
       set theYear to year
       set theMonth to its month as number
       set theDay to day
       set theHour to its hours
       set theMinutes to its minutes
       set theSeconds to its seconds
   end tell
   set begName to (theYear as text) & "-" & text -2 thru -1 of ((100 + theMonth) as text) & "-" & text -2 thru -1 of ((100 + theDay) as text) & space & text -2 thru -1 of ((100 + theHour) as text) & "." & text -2 thru -1 of ((100 + theMinutes) as text) & "." & text -2 thru -1 of ((100 + theSeconds) as text) & " Email "
   
   if sender_Name is in mySelf then
       set begName to begName & "to " & target_name
   else
       set begName to begName & "from " & sender_Name
   end if
   
   set thePDFname to begName & " - " & my supprime(mail_Subject, {":", "/"}) & ".PDF"
   set pdfPath to (path to desktop as text) & thePDFname
   
   -- Print the opened email
   
   tell application "System Events"
       tell process "Mail"
           set frontmost to true
           keystroke "p" using {command down} # Issue the Print shortcut
           tell window wName
               repeat
                   try
                       if (exists pop up button 1 of sheet 1) then exit repeat
                   end try
                   delay 0.2
               end repeat
               
               --name of menu buttons of sheet 1 of window wName
               --> {"PDF"} # but I don't know if it's spelled this way worldwide
               tell sheet 1
                   set PDFButton to first menu button
                   click PDFButton
                   -- name of menu items of menu 1 of PDFButton
                   --> {"Ouvrir le PDF dans Aperçu", "Enregistrer au format PDF…", "Enregistrer au format PostScript…", "Faxer le document PDF…", missing value, "@ PDF-BAT.qfilter", "@ PDF-prépresse CMJN.qfilter", "@ PDF-web.qfilter", "@ PDFX3-ISO.qfilter", "Add PDF to iTunes", "Envoyer le document PDF par courrier électronique", "Enregistrer le document PDF dans le dossier de reçus web", missing value, "Modifier le menu…"}
                   click menu item 2 of menu 1 of PDFButton
                   
                   repeat
                       if exists sheet 1 then exit repeat # the Print sheet exists, exit the loop!
                       delay 0.1
                   end repeat
                   
                   tell sheet 1
                       keystroke "d" using {command down} # Set the Desktop as destination folder
                       set value of text field 1 to thePDFname # Set the name of the new PDF
                       keystroke return
                   end tell # sheet 1 (the Save As one)
               end tell # sheet 1 of window wName
           end tell
       end tell # process "Mail"
       
       repeat
           if exists disk item pdfPath then exit repeat # Now the pdf is really available on the Desktop
           delay 0.1
       end repeat
   end tell # System Events
   
   # We may move the PDF to its final location
   set pdfPath to quoted form of POSIX path of pdfPath
   do shell script "mv " & pdfPath & space & quoted form of (POSIX path of attachmentsFolder)
   
   # Now speak again to Mail
   tell application "Mail"
       try
           # Here only if the message has attacments
           set num to 1
           repeat with theAttachment in eachMessage's mail attachments
               set fileName to begName & " Attachment - " & num & " - " & theAttachment's name
               save theAttachment in file (attachmentsFolder & my supprime(fileName, {":", "/"})) # I know, I'm a bit paranoid
               set num to num + 1
           end repeat
       end try
       close window wName
   end tell
end repeat # with eachMessage…

#=====
(*
removes every occurences of d in text t
*)

on supprime(t, d)
   local oTIDs, l
   set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
   set l to text items of t
   set AppleScript's text item delimiters to ""
   set t to l as text
   set AppleScript's text item delimiters to oTIDs
   return t
end supprime

#=====

I forgot that I also wrote :
Don't forget to insert your true name(s) in the instruction defining myself.

Yvan KOENIG (VALLAURIS, France) lundi 30 mars 2015 15:03:45

Last edited by Yvan Koenig (2015-03-30 01:25:07 pm)

Offline

 

#3 2015-03-30 11:13:19 am

kurttodoroff
Member
Registered: 2008-05-24
Posts: 42

Re: Save Apple Mail And Attachments As PDF

Hello, Yvan.

Thank you for your effort.  Nice work.

I will share a few observations:

1:  The script does not prompt me for a location to save the PDF.

2:  The filenames of saved PDF files of email messages that I send to recipients, should be formatted as "To" that recipient, not, "From" Kurt.

3:  I ran the script on an email message that contained an Excel file attachment.  The script saved the email message as a PDF, and, it saved the Excel file as an Excel file, instead of as a PDF.

4:  I ran the script on two email messages.  The new email message window, and, the print dialog window, became unresponsive.  They would not respond to clicks.  I force quit email, and then, relaunched it.

I will continue testing the script.

Thank you.

Kurt

Last edited by kurttodoroff (2015-03-30 11:19:51 am)

Offline

 

#4 2015-03-30 01:11:02 pm

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 4370

Re: Save Apple Mail And Attachments As PDF

Is it difficult to read what is posted ?[
(1) As you may see, I carefully wrote :  Of course you may use set attachmentsFolder to ( choose folder) as text
More, I carefully gave the instruction required to do that.

set attachmentsFolder to ( choose folder) as text

I apologize, I am able to explain what to do but I can't do it for you.

(2) As you may also see, I carefully wrote :
set mySelf to {"firstName lastName", "lastName firstName"} # I use both formats. Edit to fit your needs

It seems that you didn't edit the instruction. I can't do it for you !
It seems that your firstName is Kurt so a first step is to edit as :
set mySelf to {"Kurt lastName", "lastName Kurt"} # I use both formats. Edit to fit your needs
is quite what you need. Replace lastName by your true last name as every other reader was able to understand.

(3) I saw that you asked to save attachments as PDF but to be able to code this feature I would have to know how to drive Excel or other applications.
Excel is made by Merdosoft so it's not allowed to enter my home.
There are thousands of file types. Each of them requires its own set of instruction to be saved into PDF.
For a
spreadsheet, it would requires one PDF for each sheet

(4) As I know the limits of my script, I carefully wrote : You may try to run :
I assumed that understanding the meaning of these six words wasn't too difficult. I was wrong.

(5) After posting here, I discovered that with some documents, when we call the print process, Mail may display a sheet with the message  "Création du contenu à imprimer…" and a single button "Annuler".

The edited script is available above.

Yvan KOENIG (VALLAURIS, France) lundi 30 mars 2015 21:10:53

Last edited by Yvan Koenig (2015-03-30 01:14:42 pm)

Offline

 

#5 2019-01-26 01:16:03 pm

GG
Member
Registered: 2019-01-14
Posts: 98

Re: Save Apple Mail And Attachments As PDF

Yvan;

I've seen a few posts relating to this script. I notice that this one is from about 2015. Is this the most recent variant?

I definitely have a need to take emails and their attachments "offline". I am quite happy to have the main email in a PDF (or another format that saves links) and to have attachments in the "as-sent" format.

Offline

 

#6 2019-01-27 02:38:06 am

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 4370

Re: Save Apple Mail And Attachments As PDF

If I remember well, I have a version which saves directly in attachmentsFolder.

I will try to retrieve it but I'm a bit annoyed because I will be unable to test it with Mojave because my iMac doesn't accept this operating system.

I can't search this morning, maybe - but not guaranteed - this afternoon.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) dimanche 27 janvier 2019 09:37:59

Offline

 

#7 2019-01-27 08:42:24 am

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 4370

Re: Save Apple Mail And Attachments As PDF

You may try to run :

Applescript:

(*
https://macscripter.net/viewtopic.php?id=43790
2019/01/27
*)

my Germaine() # With this added step the script will not save globals in its file.

on Germaine()
   # =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
   
   set mySelf to {"Yvan KOENIG", "KOENIG Yvan"} # I USE BOTH FORMATS, EDIT TO FIT YOUR NEEDS
   
   # =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
   
   # Define the folder where files will be stored
   set attachmentsFolder to (choose folder) as text
   
   tell application "Mail"
       activate
       set theMessages to (get selection)
   end tell
   
   ---------------------------------------
   repeat with eachMessage in theMessages
       # Open a mail and treat it
       tell application "Mail"
           open eachMessage
           delay 0.5
           set wName to name of window 1
           
           tell eachMessage # extract datas from the selected message
               set sender_Name to extract name from its sender
               set sender_Mail to extract address from its sender
               set mail_Subject to subject
               set mail_Date to date received # will keep the time component
               set target_name to (name of its to recipient)
           end tell # the message
       end tell # application Mail
       
       # No longer speak to application Mail
       
       tell mail_Date
           set theYear to year
           set theMonth to its month as number
           set theDay to day
           set theHour to its hours
           set theMinutes to its minutes
           set theSeconds to its seconds
       end tell
       set begName to (theYear as text) & "-" & text -2 thru -1 of ((100 + theMonth) as text) & "-" & text -2 thru -1 of ((100 + theDay) as text) & space & text -2 thru -1 of ((100 + theHour) as text) & "." & text -2 thru -1 of ((100 + theMinutes) as text) & "." & text -2 thru -1 of ((100 + theSeconds) as text) -- & " Email "
       
       if sender_Name is in mySelf then
           set begName to begName & " to " & target_name
       else
           set begName to begName & " from " & sender_Name
       end if
       
       set thePDFname to begName & " - " & my remplace(mail_Subject, {":", "/"}, "-") & ".PDF" # I know, I'm a bit paranoid
       set posixFolderPath to POSIX path of attachmentsFolder
       set pdfPath to POSIX path of (posixFolderPath & thePDFname)
       
       -- Print the opened email as PDF
       tell application "System Events"
           tell process "Mail"
               set frontmost to true
               set windowName to name of window 1
               keystroke "p" using {command down} # Issue the Print shortcut
               tell window wName
                   repeat
                       try
                           if (exists pop up button 1 of sheet 1) then exit repeat
                       end try
                       delay 0.2
                   end repeat
                   
                   tell sheet 1
                       set PDFButton to first menu button
                       click PDFButton
                       tell menu 1 of PDFButton
                           name of menu items
                           --> {"Ouvrir le PDF dans Aperçu", "Enregistrer au format PDF…", "Enregistrer au format PostScript…", "Faxer le document PDF…", missing value, "@ PDF-BAT.qfilter", "@ PDF-prépresse CMJN.qfilter", "@ PDF-web.qfilter", "@ PDFX3-ISO.qfilter", "Add PDF to iTunes", "Envoyer le document PDF par courrier électronique", "Enregistrer le document PDF dans le dossier de reçus web", missing value, "Modifier le menu…"}
                           click menu item 2
                       end tell
                       repeat
                           if exists sheet 1 then exit repeat # the Print sheet exists, exit the loop!
                           delay 0.1
                       end repeat
                   end tell # sheet 1
                   
                   tell sheet 1 of sheet 1
                       set wichElements to class of UI elements
                       if wichElements contains combo box then # maybe Mojave
                           get position of combo boxes --> {{910, 118}, {910, 148}}
                           set value of combo box 1 to thePDFname
                       else -- Yosemite, El Capitan, Sierra, High Sierra
                           --> {static text, text field, UI element, static text, text field, group, radio group, group, pop up button, text field, splitter group, text field, static text, button, text field, static text, text field, static text, static text, text field, button, button, button}
                           get position of text fields --> {{1262, 194}, {1262, 224}, {1458, 263}, {1086, 646}, {1086, 616}, {1086, 552}, {1086, 584}}
                           set value of text field 1 to thePDFname
                       end if
                   end tell # sheet 1 of sheet 1
                   
                   keystroke "g" using {command down, shift down}
                   repeat until exists sheet 1 of sheet 1 of sheet 1
                       delay 0.02
                   end repeat
                   tell sheet 1 of sheet 1 of sheet 1
                       --name of UI elements
                       set wichElements to class of UI elements # According to system in use, may be
                       --> {static text, combo box, button, button} -- El Capitan, Sierra, High Sierra, maybe Mojave
                       --> {static text, text field, button, button} -- … Yosemite
                       if wichElements contains combo box then
                           set SaveIndex to -1
                           set value of combo box 1 to posixFolderPath
                       else
                           set SaveIndex to 1
                           set value of text item 1 to posixFolderPath
                       end if
                       name of buttons --> {"Aller", "Annuler"}
                       click button 1
                   end tell # sheet 1 of sheet 1 of sheet 1
                   
                   tell sheet 1 of sheet 1
                       --name of UI elements # According to system in use, may be
                       --> {"Enregistrer", "Nouveau dossier", "Annuler"}
                       --> {"Nouveau dossier", "Annuler", "Enregistrer"}
                       click button SaveIndex
                   end tell # sheet 1 of sheet 1
               end tell -- window wName
           end tell # process Mail
       end tell # "System Events"
       
       # Now speak again to application Mail
       tell application "Mail"
           try
               # Do that only if the message has attacments
               set num to 1
               repeat with theAttachment in eachMessage's mail attachments
                   set fileName to begName & " Attachment - " & num & " - " & theAttachment's name
                   save theAttachment in file (attachmentsFolder & my remplace(fileName, {":", "/"}, "-")) # I know, I'm a bit paranoid
                   set num to num + 1
               end repeat
           end try
           try
               repeat while exists window wName
                   close window wName
                   delay 0.1
               end repeat
           end try
       end tell # application Mail
   end repeat # with eachMessage…
end Germaine

#=====
(*
replace every occurences of d1 by d2 in text t
*)

on remplace(t, d1, d2)
   local oTIDs, l
   set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d1}
   set l to text items of t
   set AppleScript's text item delimiters to d2
   set t to l as text
   set AppleScript's text item delimiters to oTIDs
   return t
end remplace

#=====

I tested it only under High Sierra 10.13.6

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) dimanche 27 janvier 2019 15:41:52

Last edited by Yvan Koenig (2019-02-01 04:35:38 am)

Offline

 

#8 2019-01-30 06:27:29 pm

GG
Member
Registered: 2019-01-14
Posts: 98

Re: Save Apple Mail And Attachments As PDF

Thank you, Ivan. I had a quick look at it. Mojave will likely require me to make a few tweaks. It complains that it needs "Assistive Access". That's easily solved, But I don't know what lies beyond that. Will see what I can do and let you know.

Last edited by GG (2019-01-30 06:32:14 pm)

Offline

 

#9 2019-01-31 01:48:30 am

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 4370

Re: Save Apple Mail And Attachments As PDF

It's not only Mojave. Every OS requires Assistive Events to be enabled.
At least with Mojave and High Sierra we must do that thru the System Preference named "Security & Privacy". We must insert AppleScript in the pane entitled "Privacy".

I will made a small change to the script so that it may be more comfortable when saved as application under Mojave.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) jeudi 31 janvier 2019 08:48:22

Offline

 

#10 2019-01-31 05:39:55 pm

GG
Member
Registered: 2019-01-14
Posts: 98

Re: Save Apple Mail And Attachments As PDF

Thanks Yvan;

Just to let you know what I hope to use it for.

I receive a lot of email relating to Genealogy. I need to file these offline (eg. a NAS drive) in a way that is independent of the email program and O/S used. PDF is a great choice, providing all attachments are extracted and stored with some way of being associated with the email message. PDF also has the ability to store metadata, which means one can store the original header data inside the file, in case the file is renamed.

Will wait to see your revisions.

Offline

 

#11 2019-02-01 05:11:41 am

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 4370

Re: Save Apple Mail And Attachments As PDF

I added some instructions to be sure that every mail window is closed after treatment.

The script store the files this way :

2016-08-17 16.16.04 from H**** J********* - Re- nouveaux tests 17 aout.PDF

2016-08-17 16.21.27 to H**** J********* - Re- a titre d'info.PDF

2016-08-17 16.29.44 to H**** J********* - Re- nouveaux tests 17 aout.PDF
2016-08-17 16.29.44 to H**** J********* Attachment - 1 - resultat du test decrypteur.tiff

2016-08-17 18.12.26 from H**** J********* - Re- nouveaux tests 17 aout.PDF
2016-08-17 18.12.26 from H**** J********* Attachment - 1 - resultat du test decrypteur.tiff
2016-08-17 18.12.26 from H**** J********* Attachment - 2 - deuxieme essai.tiff
2016-08-17 18.12.26 from H**** J********* Attachment - 3 - 1 er essai.tiff

The messages are stored as PDF named from : date received, string "from" or "to", name of the correspondant, the mail subject,  the string ".PDF"
The attachments are stored in files named from : date received, string "from" or "to", name of the correspondant, the string "Attachment - ", a number which is the index of the file in the list of attached files, the string " - ", the original name of the attached file.

This way, if the contents of the folder is displayed alphabetically, it's easy to see groups of message + attached files.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) vendredi 1 février 2019 12:11:35

Offline

 

#12 2019-02-01 11:19:32 am

GG
Member
Registered: 2019-01-14
Posts: 98

Re: Save Apple Mail And Attachments As PDF

Can you post the updated code you mentioned in your last post?

It sounds like it should work for me as it is.

Regards;
Gary

Offline

 

#13 2019-02-01 11:21:54 am

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 4370

Re: Save Apple Mail And Attachments As PDF

It's available in message #7

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) vendredi 1 février 2019 18:21:49

Offline

 

#14 2019-02-01 07:48:05 pm

GG
Member
Registered: 2019-01-14
Posts: 98

Re: Save Apple Mail And Attachments As PDF

Thank you. Didn't realize that was it.

Offline

 

#15 2020-03-17 04:19:56 pm

EtienneDursel
Member
Registered: 2020-03-16
Posts: 1

Re: Save Apple Mail And Attachments As PDF

Many many thanks, it works like a breeze. 
Etienne

Offline

 

#16 2020-03-18 02:37:19 am

KniazidisR
Member
Registered: 2019-03-03
Posts: 1259

Re: Save Apple Mail And Attachments As PDF

I tested Yvan Koenig's script in the post #7. It works on the Mojave perfect.

The title of the topic should be not Save Apple Mail And Attachments As PDF, but Save Apple Mail as PDF and its Attachments as Native Format. smile In order not to confuse people. It already confused me...

Last edited by KniazidisR (2020-03-18 02:40:05 am)


Model: MacBook Pro
OS X: Catalina 10.15.4
Web Browser: Safari 13.1
Ram: 4 GB

Offline

 

#17 2020-03-18 06:43:20 am

KniazidisR
Member
Registered: 2019-03-03
Posts: 1259

Re: Save Apple Mail And Attachments As PDF

Without any GUI scripting, Apple Mail and its attachments can easily be saved in the Raw Message Format (as EML files). All markup is saved no worse than PDF. Select any message in Mail.app and run my script.

To continue the experiment, close Mail.app and double-click on the file just created to open it and to view its contents. Try even deleting the original message. An EML file should function without it.

The script:

Applescript:

set outputFile to (((path to desktop folder) as text) & "Experiment.eml")

tell application "Mail"
   set aMessage to item 1 of (get selection)
   set richSource to (source of aMessage) as rich text
end tell

try -- write text to EML file
   set fileReference to open for access file outputFile with write permission
   set eof of fileReference to 0
   write richSource to fileReference
   close access fileReference
on error
   try
       close access file outputFile
   end try
end try

Last edited by KniazidisR (2020-03-18 06:52:06 am)


Model: MacBook Pro
OS X: Catalina 10.15.4
Web Browser: Safari 13.1
Ram: 4 GB

Offline

 

#18 2020-03-18 07:00:14 am

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 4370

Re: Save Apple Mail And Attachments As PDF

I apologizes but with every attempts, I got a file whose content in Mail is :
• aucun expéditeur
(Aucun objet)

The source contained:

--0000000000004ffb9c059f12ecc0
Content-Type: multipart/alternative; boundary=\"0000000000004ffb99059f12ecbe\"

--0000000000004ffb99059f12ecbe
Content-Type: text/plain; charset=\"UTF-8\"
Content-Transfer-Encoding: quoted-printable

Bonjour

J'esp=C3=A8re  que vous allez bien  , nous avons eu le bonheur d'acqu=C3=A9=
rir une
magnifique coupe  dont  nous aimerions  avoir un peu plus de pr=C3=A9cision=
s sur
la date de sa r=C3=A9alisation.
En pi=C3=A8ce  jointe  quelques photos
Merci d'avance  pour votre retour

Cordialement
M Aqsdfg g=C3=A9rard
Wazerty


--

--0000000000004ffb99059f12ecbe
Content-Type: text/html; charset=\"UTF-8\"
Content-Transfer-Encoding: quoted-printable
<div dir=3D\"ltr\"><div>Bonjour=C2=A0 </div><div><br></div><div>J'esp=C3=




--0000000000004ffb99059f12ecbe--
--0000000000004ffb9c059f12ecc0
Content-Type: image/jpeg; name=\"gerbino papillo6.jpg\"
Content-Disposition: attachment; filename=\"gerbino papillo6.jpg\"
Content-Transfer-Encoding: base64
Content-ID: <f_k6vzr20u0>
X-Attachment-Id: f_k6vzr20u0

/9j/4AAQSkZJRgABAQAASABIAAD/4QCMRXhpZgAATU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUA
AAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAA
AEgAAAABAAOgAQADAAAAAQABAACgAgAEAAAAAQAABD6gAwAEAAAAAQAAAtQAAAAA/+0AOFBob3Rv
c2hvcCAzLjAAOEJJTQQEAAAAAAAAOEJJTQQlAAAAAAAQ1B2M2Y8AsgTpgAmY7PhCfv/AABEIAtQE

Are you using a feature which really works only with Mojave or Catalina ?

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mercredi 18 mars 2020  13:59:57

Offline

 

#19 2020-03-18 11:43:38 am

KniazidisR
Member
Registered: 2019-03-03
Posts: 1259

Re: Save Apple Mail And Attachments As PDF

Remember to check - the EML files (.eml extension files) should be opened by Mail.app.

On my system I made second test. It works too. Maybe, it is new with Mojave and Catalina. Returned content of variable richSource (it has 1 text and 1 attached jpg file, and works fine):


From: Robert Kniazidis <KNIAZIDIS.ROMPERT@gmail.com>
Content-Type: multipart/alternative;
    boundary="Apple-Mail=_4E04147C-4B26-4187-AD6D-ABD0977BD6FC"
Mime-Version: 1.0 (Mac OS X Mail 12.4 \(3445.104.11\))
Subject: Test 2
X-Universally-Unique-Identifier: 0C01257B-513B-406B-B5BB-E122DE91B678
Message-Id: <FC1ED9D9-FBC3-41CE-8B44-BB278DD26898@gmail.com>
Date: Wed, 18 Mar 2020 19:38:42 +0200
To: kniazidis.rompert@gmail.com



--Apple-Mail=_4E04147C-4B26-4187-AD6D-ABD0977BD6FC
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
    charset=us-ascii


ulk ou


--Apple-Mail=_4E04147C-4B26-4187-AD6D-ABD0977BD6FC
Content-Type: multipart/related;
    type="text/html";
    boundary="Apple-Mail=_26D4488B-BE56-4C1F-ADA7-A4B3AAB65F12"



--Apple-Mail=_26D4488B-BE56-4C1F-ADA7-A4B3AAB65F12
Content-Transfer-Encoding: 7bit
Content-Type: text/html;
    charset=us-ascii


<html><head><meta http-equiv="Content-Type" content="text/html; charset=us-ascii"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; line-break: after-white-space;" class="">ulk ou<div class=""><br class=""></div><div class=""><img apple-inline="no" id="127BAE0C-34F2-4338-B58E-A1F9E4A60ADF" src="cid:A07039ED-0F5F-4B78-9E09-153EB6BE70AF@lan" class=""></div></body></html>
--Apple-Mail=_26D4488B-BE56-4C1F-ADA7-A4B3AAB65F12
Content-Transfer-Encoding: base64
Content-Disposition: inline;
    filename="Fujifilm_FinePix_E500-Horned melon.jpg"
Content-Type: image/jpeg;
    x-unix-mode=0755;
    name="Fujifilm_FinePix_E500-Horned melon.jpg"
Content-Id: <A07039ED-0F5F-4B78-9E09-153EB6BE70AF@lan>


/9j/4AAQSkZJRgABAQEAYABgAAD/4QSERXhpZgAATU0AKgAAAAgADAEPAAIAAAAJAAAAngEQAAIA
AAAQAAAAqAESAAMAAAABAAEAAAEaAAUAAAABAAAAuAEbAAUAAAABAAAAwAEoAAMAAAABAAIAAAEx
AAIAAAALAAAAyAEyAAIAAAAUAAAA1AITAAMAAAABAAIAAIKYAAIAAAAFAAAA6IdpAAQAAAABAAAB
CsSlAAcAAAAcAAAA7gAAAABGVUpJRklMTQAARmluZVBpeCBFNTAwICAgAAAAAGAAAAABAAAAYAAA
AAFHSU1QIDIuNC41AAAyMDA4OjA3OjMxIDE2OjQ5OjEwACAgICAAAFByaW50SU0AMDI1MAAAAAIA
AgEAAAABAQAAAAAAJIKaAAUAAAABAAACwIKdAAUAAAABAAACyIgiAAMAAAABAAIAAIgnAAMAAAAB
AGQAAJAAAAcAAAAEMDIyMJADAAIAAAAUAAAC0JAEAAIAAAAUAAAC5JEBAAcAAAAEAQIDAJECAAUA
AAABAAAC+JIBAAoAAAABAAADAJICAAUAAAABAAADCJIDAAoAAAABAAADEJIEAAoAAAABAAADGJIF
AAUAAAABAAADIJIHAAMAAAABAAUAAJIIAAMAAAABAAAAAJIJAAMAAAABABAAAJIKAAUAAAABAAAD
KJJ8AAcAAAEeAAADMKAAAAcAAAAEMDEwMKABAAMAA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YBc9t0O6zc6Brsf6QNt1oaQ+8YMB3G3/AHsj5cK3Y8WmuQo+
ae3d1LIYBMT0O4/KgkLnMb3NPGDTmkEFdIYbaCeoBSSVnhdHf9tqKSSlFB4HA4dE+juIlLRypJJH
r2LFzOaA5tdLHuVWpJJMX//Z
--Apple-Mail=_26D4488B-BE56-4C1F-ADA7-A4B3AAB65F12--


--Apple-Mail=_4E04147C-4B26-4187-AD6D-ABD0977BD6FC--

Here you can see 2 EML files on my screen (opened by double-clicking (My Mail.app is empty this moment. No messages in the mailboxes at all):

33cEt.png

Last edited by KniazidisR (2020-03-18 01:26:02 pm)


Model: MacBook Pro
OS X: Catalina 10.15.4
Web Browser: Safari 13.1
Ram: 4 GB

Offline

 

#20 2020-03-18 02:16:18 pm

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 4370

Re: Save Apple Mail And Attachments As PDF

It's puzzling. In every attempts the generated file was a zero bytes one.
Five hours later, testing with the same messages, it works.
Some gremlin seems to play in my machine.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mercredi 18 mars 2020  21:16:12

Offline

 

#21 2020-03-28 11:31:23 am

fsilva.flm
Member
From:: Toronto, Ontario (Canada)
Registered: 2020-03-26
Posts: 1

Re: Save Apple Mail And Attachments As PDF

Hi Yvan,

Thank you for the script you've created. I've been looking for this for years.

I don't know to script but I was able to modify your script to save the attachments in different folders. Is there any way you can review this code and see if it can be edited to do the following:

1. Skip making a folder if there are no attachments.
2. Make this script simpler in order to increase the speed of printing and saving files in separate folders.

Thank you in advance,

Fernando Silva





my Germaine() # With this added step the script will not save globals in its file.

on Germaine()
    # =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
   
    set mySelf to {"Mr. Fernando Silva", "Silva Fernando", "Fernando Silva"} # I USE BOTH FORMATS, EDIT TO FIT YOUR NEEDS
   
    # =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
   
    # Define the folder where files will be stored
    set attachmentsFolder to (choose folder) as text
   
    tell application "Mail"
        activate
        set theMessages to (get selection)
    end tell
   
    ---------------------------------------
    repeat with eachMessage in theMessages
        # Open a mail and treat it
        tell application "Mail"
            open eachMessage
            delay 0.5
            set wName to name of window 1
           
            tell eachMessage # extract datas from the selected message
                set sender_Name to extract name from its sender
                set sender_Mail to extract address from its sender
                set mail_Subject to subject
                set mail_Date to date received # will keep the time component
                set target_name to (name of its to recipient)
            end tell # the message
        end tell # application Mail
       
        # No longer speak to application Mail
       
        tell mail_Date
            set theYear to year
            set theMonth to its month as number
            set theDay to day
            set theHour to its hours
            set theMinutes to its minutes
            set theSeconds to its seconds
        end tell
        set begName to (theYear as text) & " " & text -2 thru -1 of ((100 + theMonth) as text) & " " & text -2 thru -1 of ((100 + theDay) as text) & space & text -2 thru -1 of ((100 + theHour) as text) & "" & text -2 thru -1 of ((100 + theMinutes) as text) -- & " Email "
       
        if sender_Name is in mySelf then
            set begName to begName & " to [" & target_name & "]"
        else
            set begName to begName & " from [" & sender_Name & "]"
        end if
       
        set thePDFname to begName & " - " & my remplace(mail_Subject, {":", "/"}, "-") & ".pdf" # I know, I'm a bit paranoid
        set posixFolderPath to POSIX path of attachmentsFolder
        set pdfPath to POSIX path of (posixFolderPath & thePDFname)
       
        -- Print the opened email as PDF
        tell application "System Events"
            tell process "Mail"
                set frontmost to true
                set windowName to name of window 1
                keystroke "p" using {command down} # Issue the Print shortcut
                tell window wName
                    repeat
                        try
                            if (exists pop up button 1 of sheet 1) then exit repeat
                        end try
                        delay 0.2
                    end repeat
                   
                    tell sheet 1
                        set PDFButton to first menu button
                        click PDFButton
                        tell menu 1 of PDFButton
                            name of menu items
                            --> {"Ouvrir le PDF dans Aperçu", "Enregistrer au format PDF…", "Enregistrer au format PostScript…", "Faxer le document PDF…", missing value, "@ PDF-BAT.qfilter", "@ PDF-prépresse CMJN.qfilter", "@ PDF-web.qfilter", "@ PDFX3-ISO.qfilter", "Add PDF to iTunes", "Envoyer le document PDF par courrier électronique", "Enregistrer le document PDF dans le dossier de reçus web", missing value, "Modifier le menu…"}
                            click menu item 2
                        end tell
                        repeat
                            if exists sheet 1 then exit repeat # the Print sheet exists, exit the loop!
                            delay 0.1
                        end repeat
                    end tell # sheet 1
                   
                    tell sheet 1 of sheet 1
                        set wichElements to class of UI elements
                        if wichElements contains combo box then # maybe Mojave
                            get position of combo boxes --> {{910, 118}, {910, 148}}
                            set value of combo box 1 to thePDFname
                        else -- Yosemite, El Capitan, Sierra, High Sierra
                            --> {static text, text field, UI element, static text, text field, group, radio group, group, pop up button, text field, splitter group, text field, static text, button, text field, static text, text field, static text, static text, text field, button, button, button}
                            get position of text fields --> {{1262, 194}, {1262, 224}, {1458, 263}, {1086, 646}, {1086, 616}, {1086, 552}, {1086, 584}}
                            set value of text field 1 to thePDFname
                        end if
                    end tell # sheet 1 of sheet 1
                   
                    keystroke "g" using {command down, shift down}
                    repeat until exists sheet 1 of sheet 1 of sheet 1
                        delay 0.02
                    end repeat
                    tell sheet 1 of sheet 1 of sheet 1
                        --name of UI elements
                        set wichElements to class of UI elements # According to system in use, may be
                        --> {static text, combo box, button, button} -- El Capitan, Sierra, High Sierra, maybe Mojave
                        --> {static text, text field, button, button} -- … Yosemite
                        if wichElements contains combo box then
                            set SaveIndex to -1
                            set value of combo box 1 to posixFolderPath
                        else
                            set SaveIndex to 1
                            set value of text item 1 to posixFolderPath
                        end if
                        name of buttons --> {"Aller", "Annuler"}
                        click button 1
                    end tell # sheet 1 of sheet 1 of sheet 1
                   
                    tell sheet 1 of sheet 1
                        --name of UI elements # According to system in use, may be
                        --> {"Enregistrer", "Nouveau dossier", "Annuler"}
                        --> {"Nouveau dossier", "Annuler", "Enregistrer"}
                        click button SaveIndex
                    end tell # sheet 1 of sheet 1
                end tell -- window wName
            end tell # process Mail
        end tell # "System Events"
       
       
       
        # MAKES FOLDER
        set folderName to begName & " - " & my remplace(mail_Subject, {":", "/"}, "-") # Change the name if you wish
        set downloadFolder to attachmentsFolder # Don't change this instruction
        set attachmentsFolders to downloadFolder & folderName & ":" # Don't remove the ending colon
       
       
       
       
       
       
        tell application "System Events"
           
            if not (exists folder attachmentsFolders) then
                make new folder at end of folder downloadFolder with properties {name:folderName}
            end if
           
        end tell
       
       
       
       
       
        #SAVES ATTACHMENTS IN FOLDER
        tell application "Mail"
            set selectedMessages to the selection
            repeat with theMessage in selectedMessages
                repeat with theAttachment in theMessage's mail attachments
                    set PosixName to name of theAttachment
                    # CAUTION, if the name of the file contain some slashes,
                    # it replace them by colons. So the next instruction reset the slashs.
                    set originalName to my remplace(PosixName, ":", "/")
                    set savePath to attachmentsFolders & originalName
                   
                   
                    try
                        save theAttachment in file (savePath)
                    end try
                end repeat
            end repeat
           
            # MAKES FOLDER
            set folderName to begName & " - " & my remplace(mail_Subject, {":", "/"}, "-") # Change the name if you wish
            set downloadFolder to attachmentsFolder # Don't change this instruction
            set attachmentsFolders to downloadFolder & folderName & ":" # Don't remove the ending colon
           
           
           
           
           
           
            tell application "System Events"
               
                if not (exists folder attachmentsFolders) then
                    make new folder at end of folder downloadFolder with properties {name:folderName}
                end if
               
            end tell
           
            tell application "Finder"
                set packageFolder to attachmentsFolder
                set posixPath to quoted form of POSIX path of packageFolder
                do shell script "find " & posixPath & " -name '.DS_Store' -type f -delete && find " & posixPath & " -empty -type d -delete"
            end tell
           
            #CLOSES EMAIL WINDOWS THAT ARE OPEN
            try
                repeat while exists window wName
                    close window wName
                    delay 0.1
                end repeat
               
               
               
            end try
        end tell
    end repeat
end Germaine


#=====
(*
replace every occurences of d1 by d2 in text t
*)
on remplace(t, d1, d2)
    local oTIDs, l
    set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d1}
    set l to text items of t
    set AppleScript's text item delimiters to d2
    set t to l as text
    set AppleScript's text item delimiters to oTIDs
    return t
end remplace

#=====

----------------------------------------------------------------
--» HANLDERS
----------------------------------------------------------------
on exTant(_path) # Takes an HFS, Posix, or ~/Posix path as input.
    local _path
    try
        if _path starts with "~/" then
            set _path to (POSIX path of (path to home folder as text)) & text 3 thru -1 of _path
        end if
        if _path starts with "/" then
            alias POSIX file _path
        else if _path contains ":" then
            alias _path
        end if
        return true
    on error
        return false
    end try
end exTant
----------------------------------------------------------------

Model: MacBook Pro (Retina, 15-inch, Mid 2014)
AppleScript: 2.11 (203.1)
Browser: Safari 537.36
Operating System: macOS 10.14

Last edited by fsilva.flm (2020-03-28 11:42:14 am)

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)