github.com/bitcubate/cryptojournal@v1.2.5-0.20171102134152-f578b3d788ab/src/lib/mail/adapters/sendgrid/sendgrid.go (about) 1 package sendgrid 2 3 import ( 4 "errors" 5 6 "github.com/sendgrid/sendgrid-go" 7 "github.com/sendgrid/sendgrid-go/helpers/mail" 8 9 m "github.com/bitcubate/cryptojournal/src/lib/mail" 10 ) 11 12 // Service sends mail via sendgrid and conforms to mail.Service. 13 type Service struct { 14 from string 15 secret string 16 } 17 18 // New returns a new sendgrid Service. 19 func New(f string, s string) *Service { 20 return &Service{ 21 from: f, 22 secret: s, 23 } 24 } 25 26 // Send the given message to recipients, using the context to render it 27 func (s *Service) Send(email *m.Email) error { 28 29 if s.secret == "" { 30 return errors.New("mail: invalid mail settings") 31 } 32 33 // Set the default from if required 34 if email.ReplyTo == "" { 35 email.ReplyTo = s.from 36 } 37 38 // Check if other fields are filled in on email 39 if email.Invalid() { 40 return errors.New("mail: attempt to send invalid email") 41 } 42 43 // Create a sendgrid message with the byzantine sendgrid API 44 sendgridContent := mail.NewContent("text/html", email.Body) 45 var sendgridRecipients []*mail.Email 46 for _, r := range email.Recipients { 47 // We could possibly split recipients on <> to get email (e.g. name<example@example.com>) 48 // for now we assume they are just an email address 49 sendgridRecipients = append(sendgridRecipients, mail.NewEmail("", r)) 50 } 51 52 message := mail.NewV3Mail() 53 message.Subject = email.Subject 54 message.From = mail.NewEmail("", email.ReplyTo) 55 if email.ReplyTo != "" { 56 message.SetReplyTo(mail.NewEmail("", email.ReplyTo)) 57 } 58 p := mail.NewPersonalization() 59 p.AddTos(sendgridRecipients...) 60 message.AddPersonalizations(p) 61 message.AddContent(sendgridContent) 62 63 request := sendgrid.GetRequest(s.secret, "/v3/mail/send", "https://api.sendgrid.com") 64 request.Method = "POST" 65 request.Body = mail.GetRequestBody(message) 66 _, err := sendgrid.API(request) 67 return err 68 }