aboutsummaryrefslogtreecommitdiff
path: root/src/server/SendMail.hs
blob: f7ba3fdcb23c8460c840ad6b0e919d90e8130ce7 (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
{-# LANGUAGE OverloadedStrings #-}

module SendMail
  ( sendMail
  ) where

import Control.Arrow (left)
import Control.Exception (SomeException, try)
import Data.Either (isLeft)

import Data.Text (Text)
import Data.Text.Lazy.Builder (toLazyText, fromText)
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import qualified MimeMail as M

import Model.Mail (Mail(Mail))

sendMail :: Mail -> IO (Either Text ())
sendMail mail = 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 putStrLn "OK"
  return result

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