2017-06-26 167 views
-1

我試圖轉換mailgun curl命令來發送電子郵件給golang。這是原來的捲曲:將curl -F轉換爲golang

curl -s --user 'api:key-3ax6xnjp29jd6fds4gc373sgvjxteol0' \ 
https://api.mailgun.net/v3/samples.mailgun.org/messages \ 
-F from='Excited User <[email protected]>' \ 
-F to='[email protected]' \ 
-F subject='Hello' \ 
-F text='Testing some Mailgun awesomeness!' 

更新代碼:

var b bytes.Buffer 
    w := multipart.NewWriter(&b) 
    fw, err := w.CreateFormField("from") 
    if err != nil { 
     log.Println(err) 
    } 
    _, err = fw.Write([]byte("Excited User <[email protected]>")) 
    if err != nil { 
     log.Println(err) 
    } 

    fw, err = w.CreateFormField("to") 
    if err != nil { 
     log.Println(err) 
    } 
    _, err = fw.Write([]byte("[email protected]")) 
    if err != nil { 
     log.Println(err) 
    } 

    fw, err = w.CreateFormField("subject") 
    if err != nil { 
     log.Println(err) 
    } 
    _, err = fw.Write([]byte("Hello")) 
    if err != nil { 
     log.Println(err) 
    } 

    fw, err = w.CreateFormField("text") 
    if err != nil { 
     log.Println(err) 
    } 
    _, err = fw.Write([]byte("Testing some Mailgun awesomeness!")) 
    if err != nil { 
     log.Println(err) 
    } 

    w.Close() 

    req, err := http.NewRequest("POST", "https://api.mailgun.net/v3/samples.mailgun.org/messages", &b) 
    if err != nil { 
     log.Println(err) 
    } 
    req.SetBasicAuth("api", "key-3ax6xnjp29jd6fds4gc373sgvjxteol0") 

    req.Header.Add("Content-Type", w.FormDataContentType()) 
    // req.Header.Add("Content-Type", "application/x-www-form-urlencoded") 

    resp, err := http.DefaultClient.Do(req) 
    if err != nil { 
     log.Println(err) 
    } 
    defer resp.Body.Close() 

    fmt.Printf("Resp: %s\n", resp) 

我當然改變api:key-3ax6xnjp29jd6fds4gc373sgvjxteol0https://api.mailgun.net/v3/samples.mailgun.org/messages[email protected]我自己的API和電子郵件地址,但它似乎並沒有工作。

有人請看看我可能做錯了什麼嗎?

+0

發送郵件(而不是學習'網/ http'),你可能想Mailgun's Go SDK:https://github.com/mailgun/mailgun-go – twotwotwo

+0

@twotwotwo yeah謝謝,我之前看到過這個包,但是我覺得學習如何轉換curl命令是因爲將來會使用但也因爲包似乎要求不同的信息 – fisker

回答