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
55
56
57
58
59
60
61
62
63
64
65
|
module SendMail
( sendMail
) where
import Control.Arrow (left)
import Control.Exception (SomeException, try)
import Data.Either (isLeft)
import qualified Network.Mail.Mime as M
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as LT
import Data.Text.Lazy.Builder (fromText, toLazyText)
import Conf (Conf)
import qualified Conf
import Model.Mail (Mail (..))
sendMail :: Conf -> Mail -> IO (Either Text ())
sendMail conf mail =
if Conf.devMode conf
then
do
T.putStrLn . mockMailMessage $ mail
return (Right ())
else
do
result <- left (T.pack . show) <$> (try (M.renderSendMail . getMimeMail $ mail) :: IO (Either SomeException ()))
if isLeft result
then putStrLn ("Error sending the following email:" ++ (show mail) ++ "\n" ++ (show result))
else return ()
return result
mockMailMessage :: Mail -> Text
mockMailMessage mail = T.concat $
[ "[MOCK MAIL] "
, subject mail
, " (from: "
, from mail
, ") (to: "
, T.intercalate ", " $ to mail
, ")"
, "\n"
, body mail
]
getMimeMail :: Mail -> M.Mail
getMimeMail (Mail mailFrom mailTo mailSubject mailPlainBody) =
let fromMail = M.emptyMail (address mailFrom)
in fromMail
{ M.mailTo = map address mailTo
, M.mailParts = [ [ M.plainPart . strictToLazy $ mailPlainBody ] ]
, M.mailHeaders = [("Subject", mailSubject)]
}
address :: Text -> M.Address
address addressEmail =
M.Address
{ M.addressName = Nothing
, M.addressEmail = addressEmail
}
strictToLazy :: Text -> LT.Text
strictToLazy = toLazyText . fromText
|