daily pastebin goal
59%
SHARE
TWEET

Untitled

a guest Jan 20th, 2019 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // A representation of how the EmailTemplate struct looks like. The one used below is genereted with ProtoBuf
  2. type EmailTemplate struct {
  3.     Email    string                    
  4.     Params   map[string]string          
  5.     Template EmailTemplate_TemplateType // An enum that contains the different templates
  6. }
  7.  
  8. // Send will send a email to the user with instructions to reset their password
  9. // Returns if it's successfull or not
  10. func (c *EmailTemplateClient) Send(emailTemplate *emailservice.EmailTemplate) (bool, error) {
  11.  
  12.     templateID, err := c.getTemplateID(emailTemplate.Template)
  13.     if err != nil {
  14.         log.Warnf("Failed to match template %s to an id", emailTemplate.Template.String())
  15.         return false, ErrNoTemplateFound
  16.     }
  17.  
  18.     sendgridAPIKey := os.Getenv("SENDGRID_API_KEY")
  19.     if sendgridAPIKey == "" {
  20.         log.Warnf("No SendGrid API Key found when trying to send template %s", emailTemplate.Template.String())
  21.         return false, ErrNoAPIKey
  22.     }
  23.  
  24.     from := mail.NewEmail("Wiseer", "noreply@wiseer.io")
  25.     to := mail.NewEmail(emailTemplate.Email, emailTemplate.Email)
  26.  
  27.     message := mail.NewV3Mail()
  28.     message.SetFrom(from)
  29.     message.SetTemplateID(templateID)
  30.  
  31.     p := mail.NewPersonalization()
  32.     p.AddTos(to)
  33.     for key, value := range emailTemplate.Params {
  34.         p.SetDynamicTemplateData(key, value)
  35.     }
  36.     message.AddPersonalizations(p)
  37.  
  38.     client := sendgrid.NewSendClient(sendgridAPIKey)
  39.     response, err := client.Send(message)
  40.     if err != nil {
  41.         log.Errorf("Failed to send email template %s. %s", emailTemplate.Template.String(), err.Error())
  42.         return false, err
  43.     }
  44.     if response.StatusCode > 299 {
  45.         log.Errorf("Failed to send email template %s. Status %d, Body %s", emailTemplate.Template.String(), response.StatusCode, response.Body)
  46.         if response.StatusCode == 401 {
  47.             return false, ErrInvalidAPIKey
  48.         }
  49.         return false, ErrFailedToSend
  50.     }
  51.  
  52.     log.Infof("Successfully sent email template %s, status %d", emailTemplate.Template.String(), response.StatusCode)
  53.     return true, nil
  54. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top