New product announcement 🎉 Satori - LiveOps to know your players, deliver features, run experiments and schedule events

Sending Email Using SendGrid #

A common requirement is to be able to send email notifications to players. This can be achieved by integrating with a third-party email provider such as SendGrid.

The example snippet demonstrates how to use the nk.httpRequest function to call SendGrid’s HTTP API from from your game server. While this example focuses specifically on integrating with SendGrid, the same principle can be applied to any third-party service that provides an HTTP API.

For full SendGrid documentation on sending mail via the HTTP API see the official documentation.

Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
var headers = {
  Authorization: "Bearer <YourSendgridApiKey>",
  "Content-Type": "application/json",
};

var body = {
  personalizations: [
    {
      to: [
        {
          email: "tom@example.com",
          name: "Tom",
        },
      ],
      substitutions: {
        "-name-": "Tom",
      },
    },
    {
      to: [
        {
          email: "sean@example.com",
          name: "Sean",
        },
      ],
      substitutions: {
        "-name-": "Sean",
      },
    },
  ],
  from: {
    email: "no-reply@awesomegame.com",
    name: "Awesome Game",
  },
  subject: "Login now to receive your Daily Login Reward!",
  content: [{
    type: "text/html",
    value:
      `<p>
        Hello, -name-!<br />
        Login to Awesome Game now to receive your Daily Login Reward of 1000 Awesome Coins!
      </p>`,
  }]
};

var response = nk.httpRequest("https://api.sendgrid.com/v3/mail/send", "post", headers, JSON.stringify(body));

if (response.code != 202) {
  logger.error(response.body);
} else {
  logger.info("Successfully sent email.");
}
Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Define types
type EmailBody struct {
	Personalizations []EmailPersonalization `json:"personalizations"`
	From             EmailIdentifier        `json:"from"`
	Subject          string                 `json:"subject"`
	Content          []EmailContent         `json:"content"`
}

type EmailPersonalization struct {
	To            []EmailIdentifier `json:"to"`
	Substitutions map[string]string `json:"substitutions"`
}

type EmailIdentifier struct {
	Email string `json:"email"`
	Name  string `json:"name"`
}

type EmailContent struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

// Send an email
	emailBody := &EmailBody{
		Personalizations: []EmailPersonalization{
			{
				To: []EmailIdentifier{
					{
						Email: "tom@example.com",
						Name:  "Tom",
					},
				},
				Substitutions: map[string]string{
					"-name-": "Tom",
				},
			},
			{
				To: []EmailIdentifier{
					{
						Email: "sean@example.com",
						Name:  "Sean",
					},
				},
				Substitutions: map[string]string{
					"-name-": "Sean",
				},
			},
		},
		From: EmailIdentifier{
			Email: "no-reply@awesomegame.com",
			Name:  "Awesome Game",
		},
		Subject: "Login now to receive your Daily Login Reward!",
		Content: []EmailContent{
			{
				Type: "text/html",
				Value: `<p>
	Hello, -name-!<br />
	Login to Awesome Game now to receive your Daily Login Reward of 1000 Awesome Coins!
</p>`,
			},
		},
	}

	jsonBody, err := json.Marshal(emailBody)
	if err != nil {
		logger.Error("error marshaling email body", err)
		return err
	}

	request, err := http.NewRequest("post", "https://api.sendgrid.com/v3/mail/send", bytes.NewBuffer(jsonBody))
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Authorization", "Bearer <YourSendgridApiKey>")

	client := &http.Client{}
	response, err := client.Do(request)
	defer response.Body.Close()

	if err != nil {
		logger.Error("error making HTTP post", err)
		return err
	}

	if response.StatusCode != 202 {
		logger.Warn("failed to send email", err)
	} else {
		logger.Info("successfully sent email")
	}
Code snippet for this language Lua has not been found. Please choose another language to show equivalent examples.