1

示例代码位于:https ://sendgrid.com/blog/send-email-go-google-app-engine/

我猜这是在 Google App Engine 上使用 sendgrid-go 的非常古老的示例代码。

我尝试了 4 次排列,但每次都失败了:

https://api.sendgrid.com/v3/mail/send: http.DefaultTransport and http.DefaultClient are not available in App Engine. See https://cloud.google.com/appengine/docs/go/urlfetch/

这是带有一些日志记录的最小硬编码尝试:

package sendgridgo


import(
    "github.com/sendgrid/sendgrid-go"
    "fmt"
    _"google.golang.org/appengine"
    "net/http"
    "google.golang.org/appengine/log"
    "google.golang.org/appengine"
    "google.golang.org/appengine/urlfetch"
     _ "github.com/sendgrid/sendgrid-go/helpers/mail"
)

func init(){
    http.HandleFunc("/", IndexHandler)
    appengine.Main()
}

func IndexHandler (w http.ResponseWriter, r *http.Request){
    ctx := appengine.NewContext(r)

    log.Infof(ctx, "IndexHandler")
    sg := sendgrid.NewSendClient("SENDGRID_API_KEY")
    log.Infof(ctx, "%v", sg)
    bob := urlfetch.Client(ctx)

    log.Infof(ctx, "UrlFetchClient %v", bob)
    //resp, err := sg.Send(m)
    request := sendgrid.GetRequest("SENDGRID_API_KEY", "/v3/mail/send", "https://api.sendgrid.com")
    request.Method = "POST"

    request.Body = []byte(` {
    "personalizations": [
        {
            "to": [
                {
                    "email": "darian.hickman@gmail.com"
                }
            ],
            "subject": "Sending with SendGrid is Fun"
        }
    ],
    "from": {
        "email": "darian.hickman@villagethegame.com"
    },
    "content": [
        {
            "type": "text/plain",
            "value": "and easy to do anywhere, even with Go"
        }
    ]
}`)
    resp, err := sendgrid.API(request)

    if err != nil{
        log.Errorf(ctx, "Failed %v", err)
    }

    fmt.Fprint(w, resp)


}
4

4 回答 4

2

经过 8 次不同的尝试,包括尝试在 Google Cloud 文档中发布的使用 Sendgrid 的示例、来自 Sendgrid 博客的示例以及尝试使用已弃用的 Sendgrid api 版本,我在以下位置找到了 Sendgrid curl 示例:

https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/curl_examples.html

curl --request POST \
  --url https://api.sendgrid.com/v3/mail/send \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{"personalizations": [{"to": [{"email": "recipient@example.com"}]}],"from": {"email": "sendeexampexample@example.com"},"subject": "Hello, World!","content": [{"type": "text/plain", "value": "Heya!"}]}'

然后我将 HelloWorld 示例翻译成 URLFetch 用法

client := urlfetch.Client(ctx)

request, err := http.NewRequest("POST", "https://api.sendgrid.com/v3/mail/send", buf)
    if err != nil {
        log.Errorf(ctx, "Failed Request %v", request)
    }
    request.Header.Set("Authorization", "Bearer SENDGRID_API_KEY")
    request.Header.Set("Content-Type", "application/json")
    resp, err := client.Do(request)

一个复活节周末,稍后,它起作用了!

于 2018-04-03T00:40:36.677 回答
1

您在正确的轨道上,但跳过了sendgrid用客户端覆盖默认客户urlfetch端。

.
.
.
func IndexHandler (w http.ResponseWriter, r *http.Request){
    ctx := appengine.NewContext(r)    
    sg := sendgrid.NewSendClient("REPLACE_WITH_API_KEY")
    bob := urlfetch.Client(ctx)

    sg.Client = bob

    request := sendgrid.GetRequest("REPLACE_WITH_API_KEY", "/v3/mail/send", "https://api.sendgrid.com")
    request.Method = "POST"
.
.
.

解释

当 sendgrid 尝试使用默认net/http方法获取 url 时发生错误。

引用 AppEngine 文档

App Engine 使用 URL Fetch 服务来发出出站 HTTP(S) 请求。要发出出站 HTTP 请求,请照常使用 http 包,但使用 urlfetch.Client 创建客户端。urlfetch.Client 返回一个使用 urlfetch.Transport 的 *http.Client,它是使用 URL Fetch API 发出请求的 http.RoundTripper 接口的实现。

解决方法是覆盖 Sendgrid 客户端以使用urlfetch

        context := appengine.NewContext(r)
        sg := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY"))
        sg.Client = urlfetch.Client(context)

参考

  1. GCloud 文档 - 在 App Engine Golang 中发出 HTTP(S) 请求
于 2018-04-02T07:26:54.783 回答
1

该解决方案记录在sendgrid.go中:

// DefaultClient is used if no custom HTTP client is defined
var DefaultClient = rest.DefaultClient

因此,只需在发送开始时执行此操作,其中ctxappengine.NewContext(req)

sendgrid.DefaultClient = &rest.Client{HTTPClient: urlfetch.Client(ctx)}
于 2018-08-04T13:52:56.923 回答
0

在如何使用 Go 发送电子邮件中, SendGrid记录了在 AppEngine 上使用 Go 发送电子邮件所需的最少代码 。它与@birju-prajapati 的回答不同;客户端是用sendgrid.NewSendClient.

必须生成 API 密钥并使用您的SENDGRID_API_KEY. 然后安装sendgrid-go及其依赖项go get github.com/sendgrid/sendgrid-go

// using SendGrid's Go Library
// https://github.com/sendgrid/sendgrid-go
package main

import (
    "fmt"
    "log"
    "os"

    "github.com/sendgrid/sendgrid-go"
    "github.com/sendgrid/sendgrid-go/helpers/mail"
)

func main() {
    from := mail.NewEmail("Example User", "test@example.com")
    subject := "Sending with SendGrid is Fun"
    to := mail.NewEmail("Example User", "test@example.com")
    plainTextContent := "and easy to do anywhere, even with Go"
    htmlContent := "<strong>and easy to do anywhere, even with Go</strong>"
    message := mail.NewSingleEmail(from, subject, to, plainTextContent, htmlContent)
    client := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY"))
    response, err := client.Send(message)
    if err != nil {
        log.Println(err)
    } else {
        fmt.Println(response.StatusCode)
        fmt.Println(response.Body)
        fmt.Println(response.Headers)
    }
}
于 2020-01-03T12:48:16.423 回答