feat: fix SendgridEmailProvider error handling, fix send-email template

This commit is contained in:
Yang Luo
2024-04-11 00:18:39 +08:00
parent 3354945119
commit 6b637e3b2e
3 changed files with 69 additions and 18 deletions

View File

@ -15,6 +15,10 @@
package email
import (
"encoding/json"
"fmt"
"strings"
"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
)
@ -23,6 +27,14 @@ type SendgridEmailProvider struct {
ApiKey string
}
type SendgridResponseBody struct {
Errors []struct {
Message string `json:"message"`
Field interface{} `json:"field"`
Help interface{} `json:"help"`
} `json:"errors"`
}
func NewSendgridEmailProvider(apiKey string) *SendgridEmailProvider {
return &SendgridEmailProvider{ApiKey: apiKey}
}
@ -32,6 +44,25 @@ func (s *SendgridEmailProvider) Send(fromAddress string, fromName, toAddress str
to := mail.NewEmail("", toAddress)
message := mail.NewSingleEmail(from, subject, to, "", content)
client := sendgrid.NewSendClient(s.ApiKey)
_, err := client.Send(message)
return err
response, err := client.Send(message)
if err != nil {
return err
}
if response.StatusCode >= 300 {
var responseBody SendgridResponseBody
err = json.Unmarshal([]byte(response.Body), &responseBody)
if err != nil {
return err
}
messages := []string{}
for _, sendgridError := range responseBody.Errors {
messages = append(messages, sendgridError.Message)
}
return fmt.Errorf("SendGrid status code: %d, error message: %s", response.StatusCode, strings.Join(messages, " | "))
}
return nil
}