aboutsummaryrefslogtreecommitdiff
path: root/src/Mail.hs
blob: 83a2bbd83d40ddb586f2f9114f0358446860a7a8 (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
{-# LANGUAGE OverloadedStrings #-}

module 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 Control.Exception (SomeException, try)

import Network.Mail.Mime

import Utils.Either (mapLeft)

sendMail :: [Text] -> Text -> Text -> Text -> IO (Either Text ())
sendMail mailTo subject plainBody htmlBody = safeSendMail (mail mailTo subject plainBody htmlBody)

safeSendMail :: Mail -> IO (Either Text ())
safeSendMail mail =
  mapLeft (T.pack . show) <$> (try (renderSendMail mail) :: IO (Either SomeException ()))

mail :: [Text] -> Text -> Text -> Text -> Mail
mail mailTo subject plainBody htmlBody =
  let fromMail = emptyMail (address "no-reply@leboncoin-listener.com")
  in  fromMail
        { mailTo = map address mailTo
        , mailParts =
            [ [ plainPart . strictToLazy $ plainBody
              , htmlPart . strictToLazy $ htmlBody
              ]
            ]
        , mailHeaders = [("Subject", subject)]
        }

strictToLazy :: Text -> LT.Text
strictToLazy = toLazyText . fromText

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