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