用SendGrid发送电子邮件 #

向玩家发送电子邮件通知是一个常见的需求。这可以通过与SendGrid等第三方电子邮件服务提供商集成来实现。

以下示例片段显示如何用nk.httpRequest函数,在游戏服务器上调用SendGrid的HTTP API。虽然本示例专注于与SendGrid的集成,但相同的原则也适用于任何提供HTTP API的第三方服务。

关于通过HTTP API发送邮件的完整SendGrid文档,请参阅官方文档

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.