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

module SendMail
  ( sendMail
  ) where

import Data.Text (Text)
import qualified Data.Text as T
import Data.Either (isLeft)

import Control.Exception (SomeException, try)
import Control.Arrow (left)

import qualified Network.Mail.Mime as M

import Model.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))
    else return ()
  return result

getMimeMail :: Mail -> M.Mail
getMimeMail (Mail from to subject plainBody) =
  let fromMail = M.emptyMail (address from)
  in  fromMail
        { M.mailTo = map address to
        , M.mailParts = [ [ M.plainPart plainBody ] ]
        , M.mailHeaders = [("Subject", subject)]
        }

address :: Text -> M.Address
address addressEmail =
  M.Address
    { M.addressName = Nothing
    , M.addressEmail = addressEmail
    }