Exemplo n.º 1
0
// SendEmail sends an email through SendGrid
func (SendGridEmailer) SendEmail(to string, subject string, msg string) error {
	from := mail.NewEmail("CountMyReps", "*****@*****.**")
	// at this point, all recipients _should_ be [email protected] or [email protected]
	toName := strings.Split(to, ".")[0]
	if strings.Contains(toName, "@") {
		toName = strings.Split(toName, "@")[0]
	}
	toAddr := mail.NewEmail(toName, to)

	msg = `<img src="http://countmyreps.com/images/mustache-thin.jpg" style="margin:auto; width:300px; display:block"/>` + msg

	content := mail.NewContent("text/html", msg)
	m := mail.NewV3MailInit(from, subject, toAddr, content)

	request := sendgrid.GetRequest(os.Getenv("SENDGRID_API_KEY"), "/v3/mail/send", "https://api.sendgrid.com")
	request.Method = "POST"
	request.Body = mail.GetRequestBody(m)
	response, err := sendgrid.API(request)
	if err != nil {
		return err
	}
	if !(response.StatusCode == http.StatusOK || response.StatusCode == http.StatusAccepted) {
		return fmt.Errorf("unexpected status code from SendGrid: %d - %q", response.StatusCode, response.Body)
	}
	return nil
}
Exemplo n.º 2
0
// Minimum required to send an email
func helloEmail() []byte {

	address := "*****@*****.**"
	name := "Example User"
	from := mail.NewEmail(name, address)
	subject := "Hello World from the SendGrid Go Library"
	address = "*****@*****.**"
	name = "Example User"
	to := mail.NewEmail(name, address)
	content := mail.NewContent("text/plain", "some text here")
	m := mail.NewV3MailInit(from, subject, to, content)
	address = "*****@*****.**"
	name = "Example User"
	email := mail.NewEmail(name, address)
	m.Personalizations[0].AddTos(email)
	return mail.GetRequestBody(m)
}
Exemplo n.º 3
0
// Fully populated Mail object
func kitchenSink() []byte {
	m := mail.NewV3Mail()
	address := "*****@*****.**"
	name := "Example User"
	e := mail.NewEmail(name, address)
	m.SetFrom(e)

	m.Subject = "Hello World from the SendGrid Go Library"

	p := mail.NewPersonalization()
	tos := []*mail.Email{
		mail.NewEmail("Example User", "*****@*****.**"),
		mail.NewEmail("Example User", "*****@*****.**"),
	}
	p.AddTos(tos...)
	ccs := []*mail.Email{
		mail.NewEmail("Example User", "*****@*****.**"),
		mail.NewEmail("Example User", "*****@*****.**"),
	}
	p.AddCCs(ccs...)
	bccs := []*mail.Email{
		mail.NewEmail("Example User", "*****@*****.**"),
		mail.NewEmail("Example User", "*****@*****.**"),
	}
	p.AddBCCs(bccs...)
	p.Subject = "Hello World from the Personalized SendGrid Go Library"
	p.SetHeader("X-Test", "test")
	p.SetHeader("X-Mock", "true")
	p.SetSubstitution("%name%", "Example User")
	p.SetSubstitution("%city%", "Denver")
	p.SetCustomArg("user_id", "343")
	p.SetCustomArg("type", "marketing")
	p.SetSendAt(1461356286)
	m.AddPersonalizations(p)

	p2 := mail.NewPersonalization()
	tos2 := []*mail.Email{
		mail.NewEmail("Example User", "*****@*****.**"),
		mail.NewEmail("Example User", "*****@*****.**"),
	}
	p2.AddTos(tos2...)
	ccs2 := []*mail.Email{
		mail.NewEmail("Example User", "*****@*****.**"),
		mail.NewEmail("Example User", "*****@*****.**"),
	}
	p2.AddCCs(ccs2...)
	bccs = []*mail.Email{
		mail.NewEmail("Example User", "*****@*****.**"),
		mail.NewEmail("Example User", "*****@*****.**"),
	}
	p2.AddBCCs(bccs...)
	p2.Subject = "Hello World from the Personalized SendGrid Go Library"
	p2.SetHeader("X-Test", "test")
	p2.SetHeader("X-Mock", "true")
	p2.SetSubstitution("%name%", "Example User")
	p2.SetSubstitution("%city%", "Denver")
	p2.SetCustomArg("user_id", "343")
	p2.SetCustomArg("type", "marketing")
	p2.SetSendAt(1461356286)
	m.AddPersonalizations(p2)

	c := mail.NewContent("text/plain", "some text here")
	m.AddContent(c)

	c = mail.NewContent("text/html", "some html here")
	m.AddContent(c)

	a := mail.NewAttachment()
	a.SetContent("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12")
	a.SetType("application/pdf")
	a.SetFilename("balance_001.pdf")
	a.SetDisposition("attachment")
	a.SetContentID("Balance Sheet")
	m.AddAttachment(a)

	a2 := mail.NewAttachment()
	a2.SetContent("BwdW")
	a2.SetType("image/png")
	a2.SetFilename("banner.png")
	a2.SetDisposition("inline")
	a2.SetContentID("Banner")
	m.AddAttachment(a2)

	m.SetTemplateID("13b8f94f-bcae-4ec6-b752-70d6cb59f932")

	m.AddSection("%section1%", "Substitution Text for Section 1")
	m.AddSection("%section2%", "Substitution Text for Section 2")

	m.SetHeader("X-Test1", "1")
	m.SetHeader("X-Test2", "2")

	m.AddCategories("May")
	m.AddCategories("2016")

	m.SetCustomArg("campaign", "welcome")
	m.SetCustomArg("weekday", "morning")

	m.SetSendAt(1461356286)

	asm := mail.NewASM()
	asm.SetGroupID(99)
	asm.AddGroupsToDisplay(99)
	m.SetASM(asm)

	// This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) to work
	// m.SetBatchID("sendgrid_batch_id")

	m.SetIPPoolID("23")

	mailSettings := mail.NewMailSettings()
	bccSettings := mail.NewBCCSetting()
	bccSettings.SetEnable(true)
	bccSettings.SetEmail("*****@*****.**")
	mailSettings.SetBCC(bccSettings)
	sandBoxMode := mail.NewSetting(true)
	mailSettings.SetSandboxMode(sandBoxMode)
	bypassListManagement := mail.NewSetting(true)
	mailSettings.SetBypassListManagement(bypassListManagement)
	footerSetting := mail.NewFooterSetting()
	footerSetting.SetText("Footer Text")
	footerSetting.SetEnable(true)
	footerSetting.SetHTML("<html><body>Footer Text</body></html>")
	mailSettings.SetFooter(footerSetting)
	spamCheckSetting := mail.NewSpamCheckSetting()
	spamCheckSetting.SetEnable(true)
	spamCheckSetting.SetSpamThreshold(1)
	spamCheckSetting.SetPostToURL("https://spamcatcher.sendgrid.com")
	mailSettings.SetSpamCheckSettings(spamCheckSetting)
	m.SetMailSettings(mailSettings)

	trackingSettings := mail.NewTrackingSettings()
	clickTrackingSettings := mail.NewClickTrackingSetting()
	clickTrackingSettings.SetEnable(true)
	clickTrackingSettings.SetEnableText(true)
	trackingSettings.SetClickTracking(clickTrackingSettings)
	openTrackingSetting := mail.NewOpenTrackingSetting()
	openTrackingSetting.SetEnable(true)
	openTrackingSetting.SetSubstitutionTag("Optional tag to replace with the open image in the body of the message")
	trackingSettings.SetOpenTracking(openTrackingSetting)
	subscriptionTrackingSetting := mail.NewSubscriptionTrackingSetting()
	subscriptionTrackingSetting.SetEnable(true)
	subscriptionTrackingSetting.SetText("text to insert into the text/plain portion of the message")
	subscriptionTrackingSetting.SetHTML("<html><body>html to insert into the text/html portion of the message</body></html>")
	subscriptionTrackingSetting.SetSubstitutionTag("Optional tag to replace with the open image in the body of the message")
	trackingSettings.SetSubscriptionTracking(subscriptionTrackingSetting)
	googleAnalyticsSetting := mail.NewGaSetting()
	googleAnalyticsSetting.SetEnable(true)
	googleAnalyticsSetting.SetCampaignSource("some source")
	googleAnalyticsSetting.SetCampaignTerm("some term")
	googleAnalyticsSetting.SetCampaignContent("some content")
	googleAnalyticsSetting.SetCampaignName("some name")
	googleAnalyticsSetting.SetCampaignMedium("some medium")
	trackingSettings.SetGoogleAnalytics(googleAnalyticsSetting)
	m.SetTrackingSettings(trackingSettings)

	replyToEmail := mail.NewEmail("Example User", "*****@*****.**")
	m.SetReplyTo(replyToEmail)

	return mail.GetRequestBody(m)
}
Exemplo n.º 4
0
func (d *SendGridDriver) Send(ctx context.Context, message *notificationpb.Message, man template.Manager, ch chan<- drivers.DriverResult) {
	m := message.GetEmail()
	email := new(mail.SGMailV3)
	p := mail.NewPersonalization()
	var fromName string
	if len(m.FromName) > 0 {
		fromName = m.FromName
	} else {
		fromName = d.DefaultFromName
	}
	if len(m.FromEmail) > 0 {
		email.SetFrom(mail.NewEmail(fromName, m.FromEmail))
	} else {
		email.SetFrom(mail.NewEmail(fromName, d.DefaultFromEmail))
	}
	addName := len(m.ToEmail) == len(m.ToName)
	for i, e := range m.ToEmail {
		if addName {
			p.AddTos(mail.NewEmail(m.ToName[i], e))
		} else {
			p.AddTos(mail.NewEmail("", e))
		}
	}
	for _, e := range m.Cc {
		p.AddCCs(mail.NewEmail("", e))
	}
	for _, e := range m.Bcc {
		p.AddBCCs(mail.NewEmail("", e))
	}
	if len(m.ReplyTo) > 0 {
		email.SetReplyTo(mail.NewEmail("", m.ReplyTo))
	}
	data := make(map[string]interface{})
	if len(message.DataJson) > 0 {
		if err := json.Unmarshal(message.DataJson, &data); err != nil {
			ch <- drivers.DriverResult{Type: drivers.TypeEmail, Err: err}
			return
		}
	}
	for k, v := range message.Tags {
		if _, ok := data[k]; !ok {
			data[k] = v
		}
	}
	var err error
	email.Subject, _, err = templateString(data, m.TemplateSub, message, man, "sub", false)
	if err != nil && m.Subject == "" {
		ch <- drivers.DriverResult{Type: drivers.TypeEmail, Err: errors.New("failed to create subject text")}
		return
	}
	if email.Subject == "" {
		email.Subject = m.Subject
	}
	var html string
	var set bool
	var text string
	text, set, err = templateString(data, m.TemplateTxt, message, man, "txt", false)
	if set {
		if err != nil {
			ch <- drivers.DriverResult{Type: drivers.TypeEmail, Err: errors.New("failed to create text content")}
			return
		}
		email.AddContent(mail.NewContent("text/plain", text))
	}
	html, set, err = templateString(data, m.TemplateHtml, message, man, "html", true)
	if set {
		if err != nil {
			ch <- drivers.DriverResult{Type: drivers.TypeEmail, Err: errors.New("failed to create html content")}
			return
		}
		email.AddContent(mail.NewContent("text/html", html))
	}
	if message.ScheduleAt > 0 {
		email.SendAt = int(message.ScheduleAt)
	}
	email.AddPersonalizations(p)
	request := sendgrid.GetRequest(d.ApiKey, "/v3/mail/send", "https://api.sendgrid.com")
	request.Method = "POST"
	request.Body = mail.GetRequestBody(email)
	select {
	case <-ctx.Done():
		ch <- drivers.DriverResult{Type: drivers.TypeEmail, Err: ctx.Err()}
	default:
		r, err := sendgrid.API(request)
		if err != nil {
			ch <- drivers.DriverResult{Type: drivers.TypeEmail, Err: err}
			return
		}
		if r.StatusCode >= 300 {
			b, _ := json.Marshal(email)
			logrus.Debugf("failed to send mail: body was %s", string(b))
			ch <- drivers.DriverResult{Type: drivers.TypeEmail, Err: fmt.Errorf(r.Body)}
		} else {
			ch <- drivers.DriverResult{Type: drivers.TypeEmail, Err: nil}
		}
	}
}