-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmime-bytestring.hs
54 lines (44 loc) · 1.53 KB
/
mime-bytestring.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
{-
this parses an email and writes all attachments to the current directory
make sure you have https://github.com/np/mime-bytestring and expose the Codec.MIME.Parse.parseMIMEMessage function
also hide the mime package while your at it
ghc-pkg hide mime
ghc-pkg expose mime-bytestring
-}
import Codec.MIME.Parse
import Codec.MIME.Type
import Control.Monad
import qualified Data.ByteString.Lazy as B
import Data.List
import Data.Maybe
import System.Environment
main = do
(input:_) <- getArgs
bs <- B.readFile input
let attachments = filter isAttachment $ flatten $ parseMIMEMessage (WithoutCRLF bs)
forM_ attachments writeAttachment
flatten m = squish m []
where
squish m' xs = case mime_val_content m' of
Multi ms -> Prelude.foldr squish ms xs
Single _ -> [m']
isAttachment m = case mime_val_disp m of
Just d -> dispType d == DispAttachment
_ -> False
writeAttachment m = do
putStr $ "Writing " ++ filename ++ "... "
B.writeFile filename dat
putStrLn "(Done)"
where
filename = fromMaybe "noname.dat" (findFileName m)
dat = case mime_val_content m of
(Single bs) -> withoutCRLF bs
_ -> error "you should have never reached this code :-)"
findFileName m = case mime_val_disp m of
Just d -> case dispType d of
DispAttachment -> case find isFilename (dispParams d) of
Just (Filename name) -> Just name
Nothing -> Nothing
Nothing -> Nothing
isFilename (Filename a) = True
isFilename _ = False