1 -- |Email functions and data types.
6 import Control.Concurrent
7 import Control.Exception (evaluate)
8 import Data.List (intercalate)
9 import Data.Time (formatTime, getZonedTime)
11 import System.Locale (defaultTimeLocale, rfc822DateFormat)
13 import System.IO (hClose, hGetContents, hPutStr)
18 -- | A crude model of an RFC821 email message.
19 data Message = Message { headers :: [Header],
26 -- | The default headers attached to each message. The MIME junk is
27 -- needed for UTF-8 to work properly. Note that your mail server
28 -- should support the 8BITMIME extension.
29 default_headers :: [Header]
30 default_headers = ["MIME-Version: 1.0",
31 "Content-Type: text/plain; charset=UTF-8",
32 "Content-Transfer-Encoding: 8bit"]
34 -- | Showing a message will print it in roughly RFC-compliant
35 -- form. This form is sufficient for handing the message off to
36 -- sendmail (or compatible).
37 instance Show Message where
39 concat [ formatted_headers,
40 "Subject: " ++ (subject m) ++ "\n",
41 "From: " ++ (from m) ++ "\n",
42 "To: " ++ (to m) ++ "\n",
47 if (length (headers m) == 0)
49 else (intercalate "\n" (headers m)) ++ "\n"
52 -- |Pad a string on the left with zeros until the entire string has
54 pad_left :: String -> Int -> String
56 | n < (length str) = str
57 | otherwise = (replicate num_zeros '0') ++ str
58 where num_zeros = n - (length str)
62 -- | Constructs a 'String' in RFC822 date format for the current
64 rfc822_now :: IO String
67 return $ formatTime defaultTimeLocale rfc822DateFormat date
71 -- |Takes a message as an argument, and passes it to the system's
72 -- sendmail (or compatible) binary.
73 sendmail :: FilePath -> Message -> IO (String, String, ExitCode)
74 sendmail sendmail_path message = do
75 let sendmail_args = ["-f",
79 (inh, outh, errh, ph) <-
80 runInteractiveProcess sendmail_path sendmail_args Nothing Nothing
83 outs <- hGetContents outh
86 errs <- hGetContents errh
88 _ <- forkIO $ hPutStr inh (show message) >> hClose inh
89 _ <- forkIO $ evaluate (length outs) >> putMVar outm ()
90 _ <- forkIO $ evaluate (length errs) >> putMVar errm ()
95 ec <- waitForProcess ph
96 return (outs, errs, ec)
99 -- |The 'sendmail' function returns a three-tuple of its outputs,
100 -- errors, and exit codes. This function pretty-prints one of those
102 print_sendmail_result :: (String, String, ExitCode) -> IO ()
103 print_sendmail_result (outs, errs, ec) = do
105 ExitSuccess -> return ()
106 _ -> putStrLn $ concat ["Output: " ++ outs,
107 "\nErrors: " ++ errs,
108 "\nExit Code: " ++ (show ec)]