public
Last active

mime-mail + HaskellNet

  • Download Gist
smtp.hs
Haskell
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
import Network.Mail.Mime
 
import qualified Data.ByteString.Lazy.UTF8 as LU
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString as S
import Control.Monad
import qualified HaskellNet.SMTP as HN
import Text.Pandoc
import Text.Hamlet
import Text.XHtml.Transitional hiding ( renderHtml )
 
getMimeType = getMimeType' . reverse
 
getMimeType' ('g':'p':'j':'.':_) = "image/jpeg"
getMimeType' ('g':'e':'p':'j':'.':_) = "image/jpeg"
getMimeType' ('f':'d':'p':'.':_) = "application/pdf"
 
simpleMail to from subject body attachments =
do
readAttachments <- mapM (\x -> B.readFile x) attachments
return Mail {
mailHeaders =
[ ("To", to)
,("From", from)
,("Subject", subject)
]
, mailParts =
[
[ Part "text/plain" None Nothing $ LU.fromString $ unlines body
, Part "text/html" None Nothing $ LU.fromString $ markdownToHtml $ unlines body
-- , Part "text/html" None Nothing $ renderHtml $ toHtml $ markdownToHtml $ unlines body
]]
++
(map (\x -> [Part (getMimeType $ fst x) Base64 (Just $ fst x) $ snd x])
$ zip attachments readAttachments)
}
 
smtpServer = "outmail.f2s.com"
haskellNetSend to from subject body attachments = do
myMail <- simpleMail to from subject body attachments
con <- HN.connectSMTP smtpServer
renderedMail <- renderMail' myMail
HN.sendMail from [to] (lazyToStrict renderedMail) con
HN.closeSMTP con
 
 
lazyToStrict = S.concat . B.toChunks
 
strictToLazy = B.fromChunks . return
 
--htmlToByteString :: (HTML html) => html -> B.ByteString
--htmlToByteString = renderHtml
 
-- TODO: see if there's a way to get xhtml to go directly to ByteString
-- Hamlet has renderHtml :: Html -> ByteString
--markdownToHtml :: String -> String
markdownToHtml =
(writeHtmlString defaultWriterOptions {writerReferenceLinks = True}) .
readMarkdown defaultParserState
 
 
main = do
myMail <- simpleMail
"wrwills@gmail.com"
"mimemail@test.com"
"a test message"
[ "so much depends"
, "upon"
, "a red wheel"
, "barrow 你好"
]
["/tmp/cv.pdf", "/tmp/img.jpg"]
renderSendMail myMail
haskellNetSend "wrwills@gmail.com"
"mimemail@test.com"
"a test message"
[ "so much depends"
, "upon"
, "a red wheel"
, "barrow 你好"
]
["/tmp/cv.pdf", "/tmp/img.jpg"]
 

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.