module BuildBox.Command.Mail
( Mail(..)
, Mailer(..)
, createMailWithCurrentTime
, renderMail
, sendMailWithMailer)
where
import BuildBox.Build
import BuildBox.Pretty
import BuildBox.Command.Environment
import BuildBox.Command.System
import Data.Time.Clock
import Data.Time.LocalTime
import Data.Time.Format
import Data.Time.Calendar
import qualified Data.Text as T
data Mail
= Mail
{ mailFrom :: String
, mailTo :: String
, mailSubject :: String
, mailTime :: UTCTime
, mailTimeZone :: TimeZone
, mailMessageId :: String
, mailBody :: String }
deriving Show
data Mailer
= MailerSendmail
{ mailerPath :: FilePath
, mailerExtraFlags :: [String] }
| MailerMSMTP
{ mailerPath :: FilePath
, mailerPort :: Maybe Int }
deriving Show
createMailWithCurrentTime
:: String
-> String
-> String
-> String
-> Build Mail
createMailWithCurrentTime from to subject body
= do
utime <- io $ getCurrentTime
zone <- io $ getCurrentTimeZone
hostName <- getHostName
let dayNum = toModifiedJulianDay $ utctDay utime
let secTime = utctDayTime utime
let messageId = "<" ++ show dayNum ++ "." ++ (init $ show secTime)
++ "@" ++ hostName ++ ">"
return $ Mail
{ mailFrom = from
, mailTo = to
, mailSubject = subject
, mailTime = utime
, mailTimeZone = zone
, mailMessageId = messageId
, mailBody = body }
renderMail :: Mail -> Text
renderMail mail
= vcat
[ ppr "From: " % ppr (mailFrom mail)
, ppr "To: " % ppr (mailTo mail)
, ppr "Subject: " % ppr (mailSubject mail)
, ppr "Date: " % (ppr $ formatTime defaultTimeLocale "%a, %e %b %Y %H:%M:%S %z"
$ utcToZonedTime (mailTimeZone mail) (mailTime mail))
, ppr "Message-Id: " % ppr (mailMessageId mail)
, ppr ""
, ppr (mailBody mail) ]
sendMailWithMailer :: Mail -> Mailer -> Build ()
sendMailWithMailer mail mailer
= case mailer of
MailerSendmail{}
-> ssystemTee False
(mailerPath mailer
++ " -t ")
(T.unpack $ renderMail mail)
MailerMSMTP{}
-> ssystemTee False
(mailerPath mailer
++ " -t "
++ (maybe "" (\port -> " --port=" ++ show port) $ mailerPort mailer))
(T.unpack $ renderMail mail)