Skip to content

Instantly share code, notes, and snippets.

@wrwills
Created October 18, 2010 13:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrwills/632222 to your computer and use it in GitHub Desktop.
Save wrwills/632222 to your computer and use it in GitHub Desktop.
mime-mail + HaskellNet
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"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment