# 用SendGrid发送电子邮件

**URL:** https://heroiclabs.com/docs/zh/nakama/guides/server-framework/sendgrid/
**Summary:** 本教程演示如何通过与SendGrid集成向玩家发送电子邮件通知。

---


# 用SendGrid发送电子邮件

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

以下示例片段显示如何用[`nk.httpRequest`](../../server-framework/typescript-runtime/function-reference/#httpRequest)函数，在游戏服务器上调用SendGrid的HTTP API。虽然本示例专注于与SendGrid的集成，但相同的原则也适用于任何提供HTTP API的第三方服务。

关于通过HTTP API发送邮件的完整SendGrid文档，请参阅[官方文档](https://docs.sendgrid.com/api-reference/mail-send/mail-send)。

{{< code type="server" >}}
```typescript
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.");
}
```
{{< / code >}}

{{< code type="server" >}}
```go
// 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 >}}

{{< missing type="server" lang="lua" / >}}