1 -- |Email functions and data types.
11 import Control.Concurrent ( forkIO, newEmptyMVar, putMVar, readMVar )
12 import Control.Exception ( evaluate )
13 import Control.Monad ( liftM )
14 import Data.List ( intercalate )
15 import Data.Time ( formatTime, getZonedTime )
16 import System.Exit ( ExitCode(..) )
17 import System.Locale ( defaultTimeLocale, rfc822DateFormat )
18 import System.Process ( runInteractiveProcess, waitForProcess )
19 import System.IO ( hClose, hGetContents, hPutStr )
24 -- | A crude model of an RFC821 email message.
25 data Message = Message { headers :: [Header],
32 -- | The default headers attached to each message. The MIME junk is
33 -- needed for UTF-8 to work properly. Note that your mail server
34 -- should support the 8BITMIME extension.
35 default_headers :: [Header]
36 default_headers = ["MIME-Version: 1.0",
37 "Content-Type: text/plain; charset=UTF-8",
38 "Content-Transfer-Encoding: 8bit"]
40 -- | Showing a message will print it in roughly RFC-compliant
41 -- form. This form is sufficient for handing the message off to
42 -- sendmail (or compatible).
43 instance Show Message where
45 concat [ formatted_headers,
46 "Subject: " ++ (subject m) ++ "\n",
47 "From: " ++ (from m) ++ "\n",
48 "To: " ++ (to m) ++ "\n",
55 else (intercalate "\n" (headers m)) ++ "\n"
59 -- | Constructs a 'String' in RFC822 date format for the current
61 rfc822_now :: IO String
63 liftM (formatTime defaultTimeLocale rfc822DateFormat) getZonedTime
68 -- |Takes a message as an argument, and passes it to the system's
69 -- sendmail (or compatible) binary.
70 sendmail :: FilePath -> Message -> IO (String, String, ExitCode)
71 sendmail sendmail_path message = do
72 let sendmail_args = ["-f",
76 (inh, outh, errh, ph) <-
77 runInteractiveProcess sendmail_path sendmail_args Nothing Nothing
80 outs <- hGetContents outh
83 errs <- hGetContents errh
85 _ <- forkIO $ hPutStr inh (show message) >> hClose inh
86 _ <- forkIO $ evaluate (length outs) >> putMVar outm ()
87 _ <- forkIO $ evaluate (length errs) >> putMVar errm ()
92 ec <- waitForProcess ph
93 return (outs, errs, ec)
96 -- |The 'sendmail' function returns a three-tuple of its outputs,
97 -- errors, and exit codes. This function pretty-prints one of those
99 print_sendmail_result :: (String, String, ExitCode) -> IO ()
100 print_sendmail_result (outs, errs, ec) =
102 ExitSuccess -> return ()
103 _ -> putStrLn $ concat ["Output: " ++ outs,
104 "\nErrors: " ++ errs,
105 "\nExit Code: " ++ (show ec)]