示例代码位于: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)
}
最佳答案
经过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)
一个复活节周末,稍后,它会起作用!