blob: c649d599e2ecaecf205fc1054e1f47a77cd3ad54 (
plain)
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
|
{-# LANGUAGE OverloadedStrings #-}
module Mail
( Mail(..)
, sendMail
) where
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Text.Lazy.Builder (toLazyText, fromText)
import Data.Either (isLeft)
import Control.Exception (SomeException, try)
import qualified Network.Mail.Mime as M
data Mail = Mail
{ to :: [Text]
, subject :: Text
, plainBody :: Text
, htmlBody :: Text
} deriving (Eq, Show)
sendMail :: Mail -> IO (Either Text ())
sendMail mail = do
result <- mapLeft (T.pack . show) <$> (try (M.renderSendMail . getMimeMail $ mail) :: IO (Either SomeException ()))
if isLeft result
then putStrLn ("Error sending the following email:" ++ (show mail))
else return ()
return result
mapLeft :: (a -> c) -> Either a b -> Either c b
mapLeft f (Left l) = Left (f l)
mapLeft _ (Right r) = (Right r)
getMimeMail :: Mail -> M.Mail
getMimeMail (Mail to subject plainBody htmlBody) =
let fromMail = M.emptyMail (address "no-reply@shared-cost.guyonvarch.me")
in fromMail
{ M.mailTo = map address to
, M.mailParts =
[ [ M.plainPart . strictToLazy $ plainBody
, M.htmlPart . strictToLazy $ htmlBody
]
]
, M.mailHeaders = [("Subject", subject)]
}
strictToLazy :: Text -> LT.Text
strictToLazy = toLazyText . fromText
address :: Text -> M.Address
address addressEmail =
M.Address
{ M.addressName = Nothing
, M.addressEmail = addressEmail
}
|