IPB

Bienvenue invité ( Connexion | Inscription )

 
Reply to this topicStart new topic
> Applescript pour exporter mes mails en .eml
Options
Chris_77
posté 30 Aug 2014, 21:35
Message #1


Nouveau Membre


Groupe : Membres
Messages : 15
Inscrit : 23 May 2011
Membre no 167 564



Bonjour à tous,

alors voilà, j'enregistre mes emails sur mon disque en .eml via la fonction "enregistrer sous..." et en format "source du message brut" et j'ai voulu créer un petit script en applescript pour automatiser un peu tout ça, avec en prime un nomage du fichier particulier.

Seulement il y a un hic au niveau des pièces jointes : alors que les fichiers .eml créer "à la main" via le "enregistrer sous" contiennent bien les pièces jointes, elles sont totalement absentes des .eml obtenus via mon script. A la place j'ai un carré bleu avec un "?" à l'intérieur.

Voilà le script en question :

Code
tell application "Mail"
    set msgs to selection
    
    if length of msgs is not 0 then
        display dialog "Exporter le(s) mail(s) sélectionné(s)?"
        if the button returned of the result is "OK" then
            
            -- set up month parsing value for French Vanilla algorithm
            set fixedDate to current date --or any other date
            set month of fixedDate to January
            
            -- set theFolder
            set theFolder to choose folder with prompt "Enregistrer le(s) mail(s) exporté(s) vers..." without invisibles
            
            repeat with msg in msgs
                
                -- -- create new name prefix based on date
                set msgDate to date received of msg
                
                -- parse date
                set theYear to year of msgDate
                set theMonth to month of msgDate as integer
                set theMonth to my addZero(theMonth as string)
                set theDay to my addZero(day of msgDate as rich text)
                set hrs to my addZero(hours of msgDate as rich text)
                set mins to my addZero(minutes of msgDate as rich text)
                
                set msgDate to "[" & theYear & "." & theMonth & "." & theDay & "] [" & hrs & "h" & mins & "]"
                
                -- -- create new name sufix based on the sender
                set theSender to the (extract name from sender) of msg
                
                -- strip out funny characters that we don't want in a file name
                set comparison_string to ":/[]"
                set replacement_string to "->||"
                set msgSubject to ""
                repeat with c in (subject of msg as string)
                    set x to the offset of c in comparison_string
                    if x is not 0 then
                        set msgSubject to (msgSubject & character x of replacement_string) as string
                    else
                        set msgSubject to (msgSubject & c) as string
                    end if
                end repeat
                set msgSubject to my replaceText("Re- ", "", msgSubject)
                set msgSubject to my replaceText("Re-", "", msgSubject)
                
                set newFileName to (msgDate & " [" & theSender & "] " & msgSubject & ".eml") as Unicode text
                
                try
                    set fn to (theFolder as Unicode text) & newFileName
                    --set fn to "tmp:xxxxxxx.emlx"
                    --display dialog ("file name is: " & fn)
                    set fnid to open for access fn with write permission
                    write (get source of msg) to fnid
                    --save msg in fn -- as native format
                    close access fnid
                on error errorMessage number errorNumber
                    display dialog errorMessage & " Error #" & errorNumber as rich text buttons {"Oops"}
                end try
                
            end repeat
            -- ends processing of messages
            
            display dialog "Export de " & length of msgs & " mail(s) réussi."
        end if -- OK to export msgs
    end if -- msgs > 0
end tell

on addZero(v)
    if length of v < 2 then
        return "0" & v
    end if
    return v
end addZero

on replaceText(find, replace, subject)
    set prevTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to find
    set subject to text items of subject
    
    set text item delimiters of AppleScript to replace
    set subject to "" & subject
    set text item delimiters of AppleScript to prevTIDs
    
    return subject
end replaceText


Je vous remercie de l'aide que vous pourrez m'apporter.

Cordialement.
Go to the top of the page
 
+Quote Post
boissonnfive
posté 1 Sep 2014, 21:21
Message #2


Nouveau Membre


Groupe : Membres
Messages : 20
Inscrit : 13 Jun 2008
Membre no 116 021



Bonjour Chris_77,

j'ai une solution pour toi en utilisant le GUI scripting (manipulation de l'interface).
Pour cela, j'ai remplacé tout le code qui écrit dans le fichier :

Code
try
                    set fn to (theFolder as Unicode text) & newFileName
...
...
display dialog errorMessage & " Error #" & errorNumber as rich text buttons {"Oops"}
                end try


par :

Code
my EnregistrerSous(theFolder, newFileName)


Il faudra donc aussi ajouter le code de la fonction "EnregistrerSous" dans le fichier :

Code
on EnregistrerSous(folderDestination, fileName)
    
    set folderDestinationUnix to quoted form of POSIX path of folderDestination
    
    tell application "System Events"
        
        tell process "Mail"
            
            -- Appel du menu "Enregistrer sous..." ⇧ ⌘ S
            keystroke "s" using {shift down, command down}
            
            -- on attends un peu pour que la fenêtre s'ouvre
            delay 2.3
            
            try
                set cb1 to checkbox 1 of sheet 1 of front window
                set cb2 to checkbox 2 of sheet 1 of front window
                click cb2
            on error
                --display dialog "Format de fenêtre correct"
            end try
            
            delay 1.3
            
            -- Appel du menu "Aller à" ⇧ ⌘ G
            keystroke "g" using {shift down, command down}
            
            delay 2.3
            
            -- On écrit le chemin Unix du dossier de destination
            keystroke folderDestination
            
            delay 1.3
            
            -- On valide par "Entrée"
            keystroke return
            
            delay 2.3
            
            -- On tape le nom du fichier
            keystroke fileName
            
            delay 1.3
            
            -- on sélectionne le menu "Source du message brut"
            click pop up button 1 of group 1 of sheet 1 of front window
            
            delay 1.3
            
            click menu item 3 of menu 1 of pop up button 1 of group 1 of sheet 1 of front window
            
            -- On clique sur "Enregistrer"
            click button "Enregistrer" of sheet 1 of front window
            
            delay 2.3
            
        end tell
        
    end tell
    
end EnregistrerSous


Ça a l'air de marcher sur OS X Mavericks.

Dis-moi si ça marche pour toi aussi.

Bonne soirée.
Bruno.
Go to the top of the page
 
+Quote Post
Chris_77
posté 5 Sep 2014, 18:12
Message #3


Nouveau Membre


Groupe : Membres
Messages : 15
Inscrit : 23 May 2011
Membre no 167 564



Bonsoir.

Oui cela marche bien merci.
Mais impossible de faire de l'export de "masse" avec ce script.

Du coup je pense que le mieux serait que j'utilise le 1er script pour l'export de masse des mails sans pièces jointes, et le second pour les mails avec les pièces jointes, non ?

Merci.
Go to the top of the page
 
+Quote Post
teddy7545
posté 5 Sep 2014, 20:48
Message #4


Macbidouilleur de vermeil !
****

Groupe : Membres
Messages : 879
Inscrit : 4 Apr 2004
Lieu : Lorraine - 54
Membre no 17 184



Chris quelle taille font tes mails (ceux avec les points d'interrogation à la place des pièces jointes) sauvegardés avec ton script ?
Ont t'ils vraiment une taille différente des mails sauvegardés avec la méthode manuelle?

Je viens de tester ton script en le copiant simplement dans l'éditeur applescript et sans faire aucune modification.
Sur Maverick ton script pour exporter les mails avec des pièces jointes fonctionne pafaitement et je n'ai pas le soucis que tu décris.

D'autre personnes ont'elles testé comme moi ton script et rencontré le même problème ?


--------------------
MP Intel Dual Xéon 3 GHz - MacOSX 10.10.3 - ATI Radeon HD 5770 - ATTO UL5D - Apple Cinema HD Display 23 pouces
MBP 15' 2017 - MBP 13' mid 2009 - iMac 24' 8,1 2,8GHz - MP G4 MDD Bi 1,25 GHz - MP G4 Quicksylver 933MHz
Go to the top of the page
 
+Quote Post
Chris_77
posté 5 Sep 2014, 21:28
Message #5


Nouveau Membre


Groupe : Membres
Messages : 15
Inscrit : 23 May 2011
Membre no 167 564



Hum je viens de faire un test sur plusieurs mails et je viens de remarquer que sur certains mails j'ai bien les pièces jointes et sur d'autres non...

Pour la taille, je viens d'essayer et oui il y à bien une différence de "taille" : 67ko pour un mail obtenu via le script et qui à le pb des pièces jointes, et 200ko pour un mail obtenu via la méthode manuelle, et qui a bien la pièce jointe.

Etrange tout ça...

En tout cas merci de se pencher sur mon problème.
Go to the top of the page
 
+Quote Post
teddy7545
posté 5 Sep 2014, 22:24
Message #6


Macbidouilleur de vermeil !
****

Groupe : Membres
Messages : 879
Inscrit : 4 Apr 2004
Lieu : Lorraine - 54
Membre no 17 184



Quel est le type de fichier des pièces jointes qui ne marchent pas ?
Quelle est la taille des mails (pièces jointes comprises) des mails qui fonctionnent par rapport a ceux qui ne fonctionnent pas?
Il faudrait comprendre si le disfonctionnement vient du type des pièces jointes ou de leur taille

Demon côté j'ai essayé avec 180 de mes mails comprenant au moins une pièce jointe avec des fichiers de toutes sortes et de tailles importante (jusqu'a 9Mo) et tout fonctionne quelquesoit le type et la taille.

Ce message a été modifié par teddy7545 - 5 Sep 2014, 23:24.


--------------------
MP Intel Dual Xéon 3 GHz - MacOSX 10.10.3 - ATI Radeon HD 5770 - ATTO UL5D - Apple Cinema HD Display 23 pouces
MBP 15' 2017 - MBP 13' mid 2009 - iMac 24' 8,1 2,8GHz - MP G4 MDD Bi 1,25 GHz - MP G4 Quicksylver 933MHz
Go to the top of the page
 
+Quote Post
Chris_77
posté 11 Sep 2014, 22:06
Message #7


Nouveau Membre


Groupe : Membres
Messages : 15
Inscrit : 23 May 2011
Membre no 167 564



Désolé de cette réponse tardive...

Alors déjà un truc que je n'ai pas précisé : je suis sous OS X Mavericks.

Pour les pièces jointes qui ne fonctionnent pas : certains pdf et des photos en jpg.

Et par exemple un mail avec un pdf disfonctionnel : 6ko avec le pb de pièce jointe et 5mo avec le mail contenant bien la pièce jointe.
Go to the top of the page
 
+Quote Post
Guest_JacqR_*
posté 12 Sep 2014, 13:09
Message #8





Guests






Bonjour,

Avez-vous vérifier si le fichier-joint est téléchargé ?

Sélectionne le message avec la pièce-jointe à problème, exécute ce script:
Code
tell application "Mail" to return downloaded of mail attachments of item 1 of (get selection)
Go to the top of the page
 
+Quote Post
Chris_77
posté 12 Sep 2014, 20:37
Message #9


Nouveau Membre


Groupe : Membres
Messages : 15
Inscrit : 23 May 2011
Membre no 167 564



Citation (JacqR @ 12 Sep 2014, 14:09) *
Bonjour,

Avez-vous vérifier si le fichier-joint est téléchargé ?

Sélectionne le message avec la pièce-jointe à problème, exécute ce script:
Code
tell application "Mail" to return downloaded of mail attachments of item 1 of (get selection)


Bonjour,

mercie pour cette réponse, j'ai essayé et cela n'a rien changer confused5.gif
Go to the top of the page
 
+Quote Post
Guest_JacqR_*
posté 13 Sep 2014, 17:51
Message #10





Guests






Bonjour,

Citation (Chris_77 @ 12 Sep 2014, 15:37) *
Bonjour,

mercie pour cette réponse, j'ai essayé et cela n'a rien changer confused5.gif

Le script ne change rien, c'est juste une vérification pour trouver la raison du problème, car le script fonctionne très bien ici, mais le problème est peut-être autre chose.

Si le résultat dans la fenêtre de l'éditeur AppleScript est false sur le message qui n'enregistre pas la pièce jointe et que sur les autres messages qui fonctionnent le résultat est true, tu sauras pourquoi le script n'enregistre pas le fichier-joint de ces messages.
Go to the top of the page
 
+Quote Post
Chris_77
posté 13 Sep 2014, 20:18
Message #11


Nouveau Membre


Groupe : Membres
Messages : 15
Inscrit : 23 May 2011
Membre no 167 564



Ah d'accord, désolé...

Le résultat du script sur les mails qui ne fonctionnent pas est bien TRUE pourtant...

C'est à ni rien cimprendre...
Go to the top of the page
 
+Quote Post
Discus73
posté 8 Oct 2014, 10:25
Message #12


Nouveau Membre


Groupe : Membres
Messages : 5
Inscrit : 8 Oct 2014
Membre no 192 259



Bonjour à tous,

J'ai aussi essayé de réaliser un script pour exporter mes mails. Je suis aussi sur Mac OS X. Même si le script est différent dans sa structure (je ne suis pas développeur pro), j'ai le même souci. Dans certains cas la pièce jointe est présente dans le fichier .eml et dans d'autres cas non. Le problème est rencontré sur différents formats (ppt, pdf, xls ...). La taille de la pièce jointe ne semble pas être un probleme. Quand le phénomène se produit, le pièce attachée n'est pas incluse dans le fichier eml et est remplacée par une sorte de lien qui ne renvoie vers rien. Aussi, j'ai rajouté à mon script au démarrage le nettoyage des caches et fichiers temporaires... pour forcer le telechargement du serveur imap lors de l'enregistrement. Cela ne change rien.
Et sur un fichier à problème, le code de JacqR donne "True" 3 fois...

Toutes les idées à tester sont donc les bienvenues biggrin.gif
Go to the top of the page
 
+Quote Post
Guest_JacqR_*
posté 12 Oct 2014, 14:27
Message #13





Guests






Bonjour,

Je viens juste de penser à quelque chose, ce serait de copier le fichier ".emlx" original au lieu de de prendre le contenu du message.

Vous pouvez essayer ce script :
Code
set tot to 0
tell application "Mail"
    set msgs to selection
    if length of msgs is not 0 then
        display dialog "Exporter le(s) mail(s) sélectionné(s)?"
        set theFolder to choose folder with prompt "Enregistrer le(s) mail(s) exporté(s) vers..." without invisibles
        set comparison_string to ":/[]"
        set replacement_string to "->||"
        set tc to count comparison_string
        repeat with msg in msgs
            tell msg to set {theID, msgDate, theSender, msgSubject} to {id as string, date received, extract name from sender, subject}
            set msgDate to my formatDate(msgDate)
            
            -- strip out funny characters that we don't want in a file name
            repeat with i from 1 to tc
                set c to item i of comparison_string
                if c is in msgSubject then set msgSubject to my replaceText(c, item i of replacement_string, msgSubject)
            end repeat
            set msgSubject to my replaceText({"Re- ", "Re-"}, "", msgSubject)
            
            set newFileName to (msgDate & " [" & theSender & "] " & msgSubject & ".eml")
            if my findAndCopy(theID & ".emlx", newFileName, theFolder) then set tot to tot + 1
        end repeat
        display dialog "Export de " & tot & " sur " & (length of msgs) & "  mail(s) réussi."
    end if
end tell

on formatDate(v) --  le format iso = "2014-10-09T16:01:31" --année-mois-jour"T"heures:minutes:secondes, toujours deux chiffres pour les nombres plus petit que 10
    tell (v as «class isot» as string) to "[" & text 1 thru 4 & "." & text 6 thru 7 & "." & text 9 thru 10 & "] [" & text 12 thru 13 & "h" & text 15 thru 16 & "]"
end formatDate

on replaceText(f, r, s)
    set {tID, text item delimiters} to {text item delimiters, f}
    set s to text items of s
    set text item delimiters to r
    set s to "" & s
    set text item delimiters to tID
    return s
end replaceText

on findAndCopy(tEML, n, f)
    set x to do shell script "find ~/Library/Mail/ -mindepth 5 -type f -name " & quoted form of tEML
    if x is not "" then try
        do shell script "cp -p " & (quoted form of x) & " " & quoted form of POSIX path of ((f as text) & n)
        return true
    end try
    return false
end findAndCopy

Testez le script sur les messages qui n'enregistre pas la pièce jointe pour commencer.
Go to the top of the page
 
+Quote Post
Discus73
posté 13 Oct 2014, 16:12
Message #14


Nouveau Membre


Groupe : Membres
Messages : 5
Inscrit : 8 Oct 2014
Membre no 192 259



Bonjour JacqR,

Effectivement bonne idée.

Malheureusement, cela ne fonctionne pas avec les fameuses pièces attachées. Le message de fin "Export de 0 sur 1 mail(s) réussi." ...
J'ai testé sur d'autres mails et ton code fonctionne très bien ... sauf pour certains ... :-(

Donc le mystère reste entier. Affaire à suivre

Ce message a été modifié par Discus73 - 13 Oct 2014, 16:16.
Go to the top of the page
 
+Quote Post
Guest_JacqR_*
posté 14 Oct 2014, 18:31
Message #15





Guests






Bonjour,

Voici une autre idée à tester:
Comme "Enregistrer sous..." fonctionne bien selon les informations dans ce sujet, on va essayer de faire la même chose mais pour toute la sélection.
Donc, sélectionnez quelques messages avec pièces jointes, "Enregistrer sous..." avec comme nom "Test" sans extension (le nom est important pour tester ce nouveau script).
Garder la sélection intacte.

Exécuter ce script, il créera les fichiers ".eml" séparément selon le contenu du fichier "Test".
Code
set allNames to {}
tell application "Mail"
    set msgs to selection
    if length of msgs is not 0 then
        set theFolder to choose folder with prompt "Sélectionnez le dossier qui contient le fichier 'Test', ce fichier contient les mails 'Enregistrer sous...'." without invisibles
        set comparison_string to ":/[]"
        set replacement_string to "->||"
        set tc to count comparison_string
        repeat with msg in msgs
            tell msg to set {theID, msgDate, theSender, msgSubject} to {message id, date received, extract name from sender, subject}
            set msgDate to my formatDate(msgDate)
            
            -- strip out funny characters that we don't want in a file name
            repeat with i from 1 to tc
                set c to item i of comparison_string
                if c is in msgSubject then set msgSubject to my replaceText(c, item i of replacement_string, msgSubject)
            end repeat
            set msgSubject to my replaceText({"Re- ", "Re-"}, "", msgSubject)
            
            set end of allNames to {(msgDate & " [" & theSender & "] " & msgSubject & ".eml"), theID}
        end repeat
    end if
end tell
set tot to my createEML(theFolder, allNames)
display dialog "Export de " & tot & " sur " & (length of msgs) & "  mail(s) réussi."

on createEML(f, L)
    set tc to count L
    set p to quoted form of POSIX path of f
    do shell script "cd " & p & "; perl -e 'open($fh, \">\", \"1.eml\") or die $!;my @a;$i=0; while (<>){if (/^$/){print $fh @a; undef @a;}; push @a, $_; if (/^Message-id:/){; $i++; if ($i > 1){close $fh; open($fh, \">\", \"$i.eml\") or die $!;}; print $fh @a; undef @a}}' 'Test'"
    set j to 0
    
    repeat with k from 1 to tc
        try
            set r to do shell script "cd " & p & "; grep -A1 '^Message-id:' " & k & ".eml"
            repeat with i from 1 to tc
                if (item 2 of list i of L) is in r then tell application "System Events"
                    set name of file ("" & k & ".eml") of f to (item 1 of list i of L)
                    set j to j + 1
                end tell
            end repeat
        end try
    end repeat
    return j
end createEML

on formatDate(v) --  le format iso = "2014-10-09T16:01:31" --année-mois-jour"T"heures:minutes:secondes, toujours deux chiffres pour les nombres plus petit que 10
    tell (v as «class isot» as string) to "[" & text 1 thru 4 & "." & text 6 thru 7 & "." & text 9 thru 10 & "] [" & text 12 thru 13 & "h" & text 15 thru 16 & "]"
end formatDate

on replaceText(f, r, s)
    set {tID, text item delimiters} to {text item delimiters, f}
    set s to text items of s
    set text item delimiters to r
    set s to "" & s
    set text item delimiters to tID
    return s
end replaceText

Vérifier les fichiers ".eml" créés par le script.


Si ça fonctionne, je modifierais le script pour qu'il fasse le "Enregistrer sous..." de lui-même.
Go to the top of the page
 
+Quote Post
Discus73
posté 14 Oct 2014, 20:39
Message #16


Nouveau Membre


Groupe : Membres
Messages : 5
Inscrit : 8 Oct 2014
Membre no 192 259



Bonsoir,

Le fichier Test généré à une taille cohérente avec la sélection de mails; le mail posant problème n'étant pas le premier de la liste. Lorsque j'execute le script, j'ai une erreur dans les evenements après le premier fichier : "error "La commande s’est arrêtée avec un état non nul." et pour les mails suivants "error "grep: 2.eml: No such file or directory" et ainsi de suite 3.eml, 4.eml ... . Le script génère toutefois le fichier 1.eml qui a la taille de l'ensemble de la sélection, donc des pièces attachées. La boite de dialogue affiche ensuite "Export de 0 sur 5 mail(s) réussi."

Je sens que la solution est proche. biggrin.gif

Ce message a été modifié par Discus73 - 14 Oct 2014, 20:41.
Go to the top of the page
 
+Quote Post
Guest_JacqR_*
posté 15 Oct 2014, 00:50
Message #17





Guests






Bonsoir,

Citation (Discus73 @ 14 Oct 2014, 15:39) *
Bonsoir,

Lorsque j'execute le script, j'ai une erreur dans les evenements après le premier fichier : "error "La commande s’est arrêtée avec un état non nul." et pour les mails suivants "error "grep: 2.eml: No such file or directory" et ainsi de suite 3.eml, 4.eml ... .

Merci Discus73, avec tes informations, j'ai compris que la commande grep ne trouvait pas le texte "Message-id:".

Donc, j'ai testé sur d'autres messages (je l'avais fait sur 41 messages avant) et j'ai découvert que la casse était différente pour ce texte "Message-id:" selon les messages, dans ce cas le script ne pouvait pas séparer les messages et il ne pouvait pas renommer les fichiers.


Voici la routine à remplacer ( j'ai ajouté l'option non sensible à la casse pour les commandes qui recherche ce texte "Message-id:" )
Code
on createEML(f, L)
    set tc to count L
    set p to quoted form of POSIX path of f
    do shell script "cd " & p & "; perl -e 'open($fh, \">\", \"1.eml\") or die $!;my @a;$i=0; while (<>){if (/^$/){print $fh @a; undef @a;}; push @a, $_; if (/^Message-id:/i){; $i++; if ($i > 1){close $fh; open($fh, \">\", \"$i.eml\") or die $!;}; print $fh @a; undef @a}}' 'Test'"
    set j to 0
    
    repeat with k from 1 to tc
        try
            set r to do shell script "cd " & p & "; grep -A1 -i  '^Message-id:' " & k & ".eml"
            repeat with i from 1 to tc
                if (item 2 of list i of L) is in r then tell application "System Events"
                    set name of file ("" & k & ".eml") of f to (item 1 of list i of L)
                    set j to j + 1
                    exit repeat
                end tell
            end repeat
        end try
    end repeat
    return j
end createEML



Edition: j'ai remplacer 'test' par 'Test' dans le do shell script du script

Ce message a été modifié par JacqR - 15 Oct 2014, 01:09.
Go to the top of the page
 
+Quote Post
Discus73
posté 15 Oct 2014, 08:40
Message #18


Nouveau Membre


Groupe : Membres
Messages : 5
Inscrit : 8 Oct 2014
Membre no 192 259



Tu es un champion JacqR ! Sincèrement ! Un énorme MERCI. Sur tous mes Tests biggrin.gif cela fonctionne nickel !
Si ce n'est pas trop abuser, peux tu rajouter le enregistrez sous automatique et la supression du fichier Test ? Vu la rapidité à laquelle tu produis des scripts différents je ne peux pas lutter avec mes petites compétences d'autodidacte biggrin.gif
Merci d'avance

Pour ceux qui dans le futur voudrait utiliser le code en l' état vous le trouverez ci-dessous :
Code
set allNames to {}
tell application "Mail"
    set msgs to selection
    if length of msgs is not 0 then
        set theFolder to choose folder with prompt "Sélectionnez le dossier qui contient le fichier 'Test', ce fichier contient les mails 'Enregistrer sous...'." without invisibles
        set comparison_string to ":/[]"
        set replacement_string to "->||"
        set tc to count comparison_string
        repeat with msg in msgs
            tell msg to set {theID, msgDate, theSender, msgSubject} to {message id, date received, extract name from sender, subject}
            set msgDate to my formatDate(msgDate)
            
            -- strip out funny characters that we don't want in a file name
            repeat with i from 1 to tc
                set c to item i of comparison_string
                if c is in msgSubject then set msgSubject to my replaceText(c, item i of replacement_string, msgSubject)
            end repeat
            set msgSubject to my replaceText({"Re- ", "Re-"}, "", msgSubject)
            
            set end of allNames to {(msgDate & " [" & theSender & "] " & msgSubject & ".eml"), theID}
        end repeat
    end if
end tell
set tot to my createEML(theFolder, allNames)
display dialog "Export de " & tot & " sur " & (length of msgs) & "  mail(s) réussi."

on createEML(f, L)
    set tc to count L
    set p to quoted form of POSIX path of f
    do shell script "cd " & p & "; perl -e 'open($fh, \">\", \"1.eml\") or die $!;my @a;$i=0; while (<>){if (/^$/){print $fh @a; undef @a;}; push @a, $_; if (/^Message-id:/i){; $i++; if ($i > 1){close $fh; open($fh, \">\", \"$i.eml\") or die $!;}; print $fh @a; undef @a}}' 'Test'"
    set j to 0
    
    repeat with k from 1 to tc
        try
            set r to do shell script "cd " & p & "; grep -A1 -i  '^Message-id:' " & k & ".eml"
            repeat with i from 1 to tc
                if (item 2 of list i of L) is in r then tell application "System Events"
                    set name of file ("" & k & ".eml") of f to (item 1 of list i of L)
                    set j to j + 1
                    exit repeat
                end tell
            end repeat
        end try
    end repeat
    return j
end createEML

on formatDate(v) --  le format iso = "2014-10-09T16:01:31" --année-mois-jour"T"heures:minutes:secondes, toujours deux chiffres pour les nombres plus petit que 10
    tell (v as «class isot» as string) to "[" & text 1 thru 4 & "." & text 6 thru 7 & "." & text 9 thru 10 & "] [" & text 12 thru 13 & "h" & text 15 thru 16 & "]"
end formatDate

on replaceText(f, r, s)
    set {tID, text item delimiters} to {text item delimiters, f}
    set s to text items of s
    set text item delimiters to r
    set s to "" & s
    set text item delimiters to tID
    return s
end replaceText


excl.gif Avec ce code, pensez à enregistrer la sélection avec le nom Test

Ce message a été modifié par Discus73 - 15 Oct 2014, 09:12.
Go to the top of the page
 
+Quote Post
Guest_JacqR_*
posté 15 Oct 2014, 14:58
Message #19





Guests






Bonjour,

Voici le script qui utilise le menu "Enregistrer sous..." pour exporter les messages sélectionnés, le fichier qui contient le contenu de tous les messages sélectionnés sera supprimé (et il sera dans un dossier temporaire pour ne pas avoir de problème avec les noms des éléments dans un dossier existant).
L'accessibilité doit-être activé pour que le script fonctionne.


Code
set allNames to {}
tell application "Mail"
    set msgs to selection
    if length of msgs is not 0 then
        set theFolder to choose folder with prompt "Enregistrer le(s) mail(s) exporté(s) vers..." & return & "Ne touchez pas au clavier tant que la fenêtre 'Enregistrer sous' ne sera pas fermer."
        set tmpFolder to my createTempFolder()
        if my saveAs(tmpFolder) then -- réussi
            set comparison_string to ":/[]"
            set replacement_string to "->||"
            set tc to count comparison_string
            repeat with msg in msgs
                tell msg to set {theID, msgDate, theSender, msgSubject} to {message id, date received, extract name from sender, subject}
                set msgDate to my formatDate(msgDate)
                
                -- strip out funny characters that we don't want in a file name
                repeat with i from 1 to tc
                    set c to item i of comparison_string
                    if c is in msgSubject then set msgSubject to my replaceText(c, item i of replacement_string, msgSubject)
                end repeat
                set msgSubject to my replaceText({"Re- ", "Re-"}, "", msgSubject)
                set end of allNames to {(msgDate & " [" & theSender & "] " & msgSubject & ".eml"), theID}
            end repeat
        else
            display dialog "Problème avec 'Enregistrer sous' par l'interface de 'Mail'" buttons {"OK"}
            my delTempFolder(tmpFolder) -- supprime le dossier créé dans le dossier temporaire
            return
        end if
    end if
end tell
set tot to my createEML(theFolder, allNames, tmpFolder)
activate
display dialog "Export de " & tot & " sur " & (length of msgs) & "  mail(s) réussi."

on createEML(f, L, tmpF)
    set tc to count L
    set p to quoted form of POSIX path of f
    -- sépare les messages dans le fichier enregistré et je les mets dans des fichiers "i.emlz" (pour n'avoir aucun problème avec les noms des autres fichiers ".eml" dans le dossier)
    do shell script "cd " & p & "; perl -e 'open($fh, \">\", \"1.emlz\") or die $!;my @a;$i=0; while (<>){if (/^$/){print $fh @a; undef @a;}; push @a, $_; if (/^Message-id:/i){; $i++; if ($i > 1){close $fh; open($fh, \">\", \"$i.emlz\") or die $!;}; print $fh @a; undef @a}}' " & quoted form of (tmpF & "allSelMsgs.eml")
    set j to 0
    my delTempFolder(tmpF) -- supprime le dossier créé (il contient le fichier "allSelMsgs.eml") dans le dossier temporaire
    
    repeat with k from 1 to tc
        try -- on récupère les deux lignes pour identifier le message , on renomme le fichier avec le nom correspondant dans la liste.
            set theID to do shell script "cd " & p & "; grep -A1 -i  '^Message-id:' " & k & ".emlz" --(quelque fois l'identification est dans la ligne suivante de la ligne qui commence par "Message-id:")
            repeat with i from 1 to tc
                if (item 2 of list i of L) is in theID then tell application "System Events" -- on vérifie que la variable theID correspond avec le message id
                    set name of file ("" & k & ".emlz") of f to (item 1 of list i of L) -- renomme le fichier
                    set j to j + 1
                    exit repeat
                end tell
            end repeat
        end try
    end repeat
    return j
end createEML

on formatDate(v) --  le format iso = "2014-10-09T16:01:31" --année-mois-jour"T"heures:minutes:secondes, toujours deux chiffres pour les nombres plus petit que 10
    tell (v as «class isot» as string) to "[" & text 1 thru 4 & "." & text 6 thru 7 & "." & text 9 thru 10 & "] [" & text 12 thru 13 & "h" & text 15 thru 16 & "]"
end formatDate

on replaceText(f, r, s)
    set {tID, text item delimiters} to {text item delimiters, f}
    set s to text items of s
    set text item delimiters to r
    set s to "" & s
    set text item delimiters to tID
    return s
end replaceText

on saveAs(f) -- on enregistre la selection
    tell application "System Events"
        tell process "Mail"
            set frontmost to true
            keystroke "s" using {shift down, command down}
            tell sheet 1 of front window -- dialogue "Enregistrer sous"
                set i to 0
                repeat until exists
                    delay 1
                    set i to i + 1
                    if i > 6 then return false --Après 6 secondes, Enregistrer sous ne s'affiche pas , on sort
                end repeat
                set i to 0
                keystroke "allSelMsgs.eml" -- le nom du fichier
                keystroke "g" using {shift down, command down}
                repeat until exists (sheet 1) -- dialogue "Aller au dossier"
                    delay 0.5
                    set i to i + 1
                    if i > 10 then return false --Après 5 secondes,"Aller au dossier" ne s'affiche pas , on sort
                end repeat
                keystroke f & return
                repeat while exists (sheet 1)
                    delay 0.5
                end repeat -- fermeture du dialogue "Aller au dossier"
                -- on sélectionne le menu "Source du message brut", si ce n'est pas déjà le cas
                tell pop up button 1 of group 1 to if value is not "Source du message brut" then
                    click
                    repeat until exists (menu 1)
                        delay 0.2
                    end repeat
                    click menu item 3 of menu 1
                end if
                click button "Enregistrer"
                repeat while exists
                    delay 0.5
                end repeat -- fermeture du dialogue "Enregistrer sous"
                return true
            end tell
        end tell
    end tell
end saveAs

on createTempFolder()
    set D to quoted form of POSIX path of (path to temporary items)
    repeat -- creation du dossier temporaire, les X =  la commande ajoutera divers caractères dans le nom selon un random
        tell (do shell script "/usr/bin/mktemp  -d " & D & "'_SelMsgsDossierTemporaireXXXXXXXXXXXXXXXX'") to if it is not "" then return (it & "/") -- chemin du dossier créé
    end repeat
end createTempFolder
on delTempFolder(f)
    do shell script "/bin/rm -r " & (quoted form of f) & "> /dev/null 2>&1 &"
end delTempFolder


Edition: ajout de l'option -r dans la commande rm

Ce message a été modifié par JacqR - 15 Oct 2014, 16:19.
Go to the top of the page
 
+Quote Post
Discus73
posté 15 Oct 2014, 15:29
Message #20


Nouveau Membre


Groupe : Membres
Messages : 5
Inscrit : 8 Oct 2014
Membre no 192 259



Un très grand merci JacqR !!!
Ca a l'air de fonctionner parfaitement de mon côté. Si Chris_77 peut confirmer ...
Je pense que le sujet est clos laugh.gif
Go to the top of the page
 
+Quote Post
Guest_JacqR_*
posté 15 Oct 2014, 16:03
Message #21





Guests






J'ai oublié d'ajouter l'option -r dans la commande rm , c'est nécessaire quand on veut supprimer un dossier, sinon cela ne fait rien.
Code
on delTempFolder(f)
    do shell script "/bin/rm -r " & (quoted form of f) & "> /dev/null 2>&1 &"
end delTempFolder


Aussi, je corrige cela dans le script de mon message originale.
Go to the top of the page
 
+Quote Post
Chris_77
posté 19 Oct 2014, 16:09
Message #22


Nouveau Membre


Groupe : Membres
Messages : 15
Inscrit : 23 May 2011
Membre no 167 564



Bonjour à tous,

Le script proposé par JacqR fonctionne très bien, la seule fois ou je le met en défaut c'est quand il n'y a qu'1 seul mail de selectionné, là l'exportation échoue.

Mais peut être que ce comportement est normal.
Go to the top of the page
 
+Quote Post
Guest_JacqR_*
posté 19 Oct 2014, 21:21
Message #23





Guests






Bonjour,

Citation (Chris_77 @ 19 Oct 2014, 11:09) *
Bonjour à tous,

Le script proposé par JacqR fonctionne très bien, la seule fois ou je le met en défaut c'est quand il n'y a qu'1 seul mail de selectionné, là l'exportation échoue.

Mais peut être que ce comportement est normal.


J'avais oublié que la sélection pouvait-être qu'un seul message biggrin.gif :
Dans ce cas, Mail ajoutait l'extension ".eml" automatiquement (ce qui donne "allSelMsgs.eml.eml"), donc la commande perl ne pouvait pas trouver ce fichier, et la commande avait besoin d'au moins deux messages pour pouvoir faire la séparation.

Voici le script modifié qui gère toutes les possibilitées de la sélection dans Mail (aucun, un seul ou multiple message) :
Code
set allNames to {}
tell application "Mail"
    set msgs to selection
    if msgs is not {} then
        set theFolder to choose folder with prompt "Enregistrer le(s) mail(s) exporté(s) vers..." & return & "Ne touchez pas au clavier tant que la fenêtre 'Enregistrer sous' ne sera pas fermer."
        set tmpFolder to my createTempFolder()
        if my saveAs(tmpFolder) then -- réussi
            set comparison_string to ":/[]"
            set replacement_string to "->||"
            set tc to count comparison_string
            repeat with msg in msgs
                tell msg to set {theID, msgDate, theSender, msgSubject} to {message id, date received, extract name from sender, subject}
                set msgDate to my formatDate(msgDate)
                
                repeat with i from 1 to tc -- strip out funny characters that we don't want in a file name
                    set c to item i of comparison_string
                    if c is in msgSubject then set msgSubject to my replaceText(c, item i of replacement_string, msgSubject)
                end repeat
                set msgSubject to my replaceText({"Re- ", "Re-"}, "", msgSubject)
                set end of allNames to {(msgDate & " [" & theSender & "] " & msgSubject & ".eml"), theID}
            end repeat
        else
            my delTempFolder(tmpFolder) -- supprime le dossier créé dans le dossier temporaire
            display dialog "Problème avec 'Enregistrer sous' par l'interface de 'Mail'" buttons {"OK"} cancel button 1 default button 1
        end if
    else
        display dialog "Aucun message de sélectionné" buttons {"OK"} cancel button 1 default button 1
    end if
end tell
set tot to my createEML(theFolder, allNames, tmpFolder)
activate
display dialog "Export de " & tot & " sur " & (length of msgs) & "  mail(s) réussi."

on createEML(f, L, tmpF)
    set tc to count L
    set p to quoted form of POSIX path of f
    -- sépare les messages dans le fichier enregistré et je les mets dans des fichiers "i.emlz" (pour n'avoir aucun problème avec les noms des autres fichiers ".eml" dans le dossier)
    do shell script "cd " & p & "; perl -e 'open($fh, \">\", \"1.emlz\") or die $!;my @a;$i=0; while (<>){if (/^$/){print $fh @a; undef @a;}; push @a, $_; if (/^Message-id:/i){; $i++; if ($i > 1){close $fh; open($fh, \">\", \"$i.emlz\") or die $!;}; print $fh @a; undef @a}}; if (@a){print $fh @a; close $fh;}' " & (quoted form of (tmpF & "allSelMsgs.eml")) & "*"
    set j to 0
    my delTempFolder(tmpF) -- supprime le dossier créé (il contient le fichier "allSelMsgs.eml") dans le dossier temporaire
    repeat with k from 1 to tc
        try -- on récupère les deux lignes pour identifier le message , on renomme le fichier avec le nom correspondant dans la liste.
            set theID to do shell script "cd " & p & "; grep -A1 -i  '^Message-id:' " & k & ".emlz" --(quelque fois l'identification est dans la ligne suivante de la ligne qui commence par "Message-id:")
            repeat with i from 1 to tc
                if (item 2 of list i of L) is in theID then tell application "System Events" -- on vérifie que la variable theID correspond avec le message id
                    set name of file ("" & k & ".emlz") of f to (item 1 of list i of L) -- renomme le fichier
                    set j to j + 1
                    exit repeat
                end tell
            end repeat
        end try
    end repeat
    return j
end createEML

on formatDate(v) --  le format iso = "2014-10-09T16:01:31" --année-mois-jour"T"heures:minutes:secondes, toujours deux chiffres pour les nombres plus petit que 10
    tell (v as «class isot» as string) to "[" & text 1 thru 4 & "." & text 6 thru 7 & "." & text 9 thru 10 & "] [" & text 12 thru 13 & "h" & text 15 thru 16 & "]"
end formatDate

on replaceText(f, r, s)
    set {tID, text item delimiters} to {text item delimiters, f}
    set s to text items of s
    set text item delimiters to r
    set s to "" & s
    set text item delimiters to tID
    return s
end replaceText

on saveAs(f) -- on enregistre la selection
    tell application "System Events"
        tell process "Mail"
            set frontmost to true
            keystroke "s" using {shift down, command down}
            tell sheet 1 of front window -- dialogue "Enregistrer sous"
                set i to 0
                repeat until exists
                    delay 1
                    set i to i + 1
                    if i > 6 then return false --Après 6 secondes, Enregistrer sous ne s'affiche pas , on sort
                end repeat
                set i to 0
                keystroke "allSelMsgs.eml" -- le nom du fichier
                keystroke "g" using {shift down, command down}
                repeat until exists (sheet 1) -- dialogue "Aller au dossier"
                    delay 0.5
                    set i to i + 1
                    if i > 10 then return false --Après 5 secondes,"Aller au dossier" ne s'affiche pas , on sort
                end repeat
                keystroke f & return
                try -- quelquefois le sheet est fermé avant que la ligne suivante s'execute
                    repeat while exists (sheet 1)
                        delay 0.5
                    end repeat -- fermeture du dialogue "Aller au dossier"
                end try
                -- on sélectionne le menu "Source du message brut", si ce n'est pas déjà le cas
                tell pop up button 1 of group 1 to if value is not "Source du message brut" then
                    click
                    repeat until exists (menu 1)
                        delay 0.2
                    end repeat
                    click menu item 3 of menu 1
                end if
                click button "Enregistrer"
                repeat while exists
                    delay 0.5
                end repeat -- fermeture du dialogue "Enregistrer sous"
                return true
            end tell
        end tell
    end tell
end saveAs

on createTempFolder()
    set D to quoted form of POSIX path of (path to temporary items)
    repeat -- creation du dossier temporaire, les X =  la commande ajoutera divers caractères dans le nom selon un random
        tell (do shell script "/usr/bin/mktemp  -d " & D & "'_SelMsgsDossierTemporaireXXXXXXXXXXXXXXXX'") to if it is not "" then return (it & "/") -- chemin du dossier créé
    end repeat
end createTempFolder
on delTempFolder(f)
    do shell script "/bin/rm -r " & (quoted form of f) & "> /dev/null 2>&1 &"
end delTempFolder
Go to the top of the page
 
+Quote Post
Chris_77
posté 19 Oct 2014, 21:54
Message #24


Nouveau Membre


Groupe : Membres
Messages : 15
Inscrit : 23 May 2011
Membre no 167 564



Avec cette version tout fonctionne parfaitement.

Un grand merci JacqR pour ce script.

Et en ce qui me concerne mon pb est résolu ^^
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic
1 utilisateur(s) sur ce sujet (1 invité(s) et 0 utilisateur(s) anonyme(s))
0 membre(s) :

 



Nous sommes le : 23rd April 2024 - 20:13