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.