Last active
January 19, 2019 13:37
-
-
Save johan-lejdung/64adc652f464768b476219410a7e2ce3 to your computer and use it in GitHub Desktop.
Made in response to https://github.com/sendgrid/sendgrid-go/issues/325
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A representation of how the EmailTemplate struct looks like. The one used below is genereted with ProtoBuf | |
type EmailTemplate struct { | |
Email string | |
Params map[string]string | |
Template EmailTemplate_TemplateType // An enum that contains the different templates | |
} | |
// Send will send a email to the user with instructions to reset their password | |
// Returns if it's successfull or not | |
func (c *EmailTemplateClient) Send(emailTemplate *emailservice.EmailTemplate) (bool, error) { | |
templateID, err := c.getTemplateID(emailTemplate.Template) | |
if err != nil { | |
log.Warnf("Failed to match template %s to an id", emailTemplate.Template.String()) | |
return false, ErrNoTemplateFound | |
} | |
sendgridAPIKey := os.Getenv("SENDGRID_API_KEY") | |
if sendgridAPIKey == "" { | |
log.Warnf("No SendGrid API Key found when trying to send template %s", emailTemplate.Template.String()) | |
return false, ErrNoAPIKey | |
} | |
from := mail.NewEmail("Wiseer", "[email protected]") | |
to := mail.NewEmail(emailTemplate.Email, emailTemplate.Email) | |
message := mail.NewV3Mail() | |
message.SetFrom(from) | |
message.SetTemplateID(templateID) | |
p := mail.NewPersonalization() | |
p.AddTos(to) | |
for key, value := range emailTemplate.Params { | |
p.SetDynamicTemplateData(key, value) | |
} | |
message.AddPersonalizations(p) | |
client := sendgrid.NewSendClient(sendgridAPIKey) | |
response, err := client.Send(message) | |
if err != nil { | |
log.Errorf("Failed to send email template %s. %s", emailTemplate.Template.String(), err.Error()) | |
return false, err | |
} | |
if response.StatusCode > 299 { | |
log.Errorf("Failed to send email template %s. Status %d, Body %s", emailTemplate.Template.String(), response.StatusCode, response.Body) | |
if response.StatusCode == 401 { | |
return false, ErrInvalidAPIKey | |
} | |
return false, ErrFailedToSend | |
} | |
log.Infof("Successfully sent email template %s, status %d", emailTemplate.Template.String(), response.StatusCode) | |
return true, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment