Using tls-extra for simple smtp

后端 未结 2 1819
礼貌的吻别
礼貌的吻别 2021-02-14 18:47

I am trying to write a simple script to send a mail via my gmail account. But I am a beginner so it is not that simple. I tryed google but exept for hackage, there is no help or

2条回答
  •  攒了一身酷
    2021-02-14 19:14

    You could use the connection package which simplify client connection and provide all the necessary bits for this. The following code will works to connect to smtp.gmail.com:

    {-# LANGUAGE OverloadedStrings #-}
    import qualified Data.ByteString as B
    import Data.ByteString.Char8 ()
    import Network.Connection
    import Data.Default
    
    readHeader con = do
        l <- connectionGetLine 1024 con
        putStrLn $ show l
        if B.isPrefixOf "250 " l
            then return ()
            else readHeader con
    
    main = do
        ctx <- initConnectionContext
        con <- connectTo ctx $ ConnectionParams
                                { connectionHostname  = "smtp.gmail.com"
                                , connectionPort      = 25
                                , connectionUseSecure = Nothing
                                , connectionUseSocks  = Nothing
                                }
    
        -- read the server banner
        connectionGetLine 1024 con >>= putStrLn . show
        -- say ehlo to the smtp server
        connectionPut con "EHLO\n"
        -- wait for a reply and print
        readHeader con
        -- Tell the server to start a TLS context.
        connectionPut con "STARTTLS\n"
        -- wait for a reply and print
        connectionGetLine 1024 con >>= putStrLn . show
    
        -- negociate the TLS context
        connectionSetSecure ctx con def
    
        ------- connection is secure now
        -- send credential, passwords, ask question, etc.
    
        -- then quit politely.
        connectionPut con "QUIT\n"
        connectionClose con
    

提交回复
热议问题