Code

Allows players to manage in-game mail

Overview

Here is everything needed to use the Mail feature in the "Beamable SDK for Unity".

The purpose of this feature is to allow players to manage in-game MailMail - A message sent from a player to a player messages.

Messaging the game players can have a significant multiplier effect on engagement and revenue. This feature is designed to narrowcast communications (e.g. 1 to 1) between players.

Related Features

📘

Messaging

Messaging the game players can have a significant multiplier effect on engagement and revenue. Beamable offers features to support this.

1. Announcements - Allows players to manage announcements. This is designed to broadcast communications (e.g. 1 to many). See Announcements for more info

2. Notifications - Allows game makers to message players, regardless if game is running. This is designed to broadcast communications (e.g. 1 to many). See Notifications for more info

3. Mail - Allows players to manage in-game mail messages. This is designed to narrowcast communications (e.g. 1 to 1). Continue reading below for more info

API

Unlike many Beamable FeatureFeature - An individual aspect of the Beamable product used to create a great user experiences, Mail does not require a specific Beamable Feature PrefabFeature Prefab - The drag-and-drop template for a specific Beamable product feature to be used. The main entry point to this feature is C# programming.

📘

Learning Fundamentals

Game makers who are new to Unity and C# can review the fundamentals here.

• See Beamable: Asynchronous Programming for more info

Here are API highlights for beamableAPI.MailService.

This is the main functionality related to MailMail - A message sent from a player to a player messages.

Method Name

Detail

GetCurrent

Fetches the count of unread MailMessage objects

GetMail

Fetches a list of MailMessage objects

SearchMail

Fetches a list of filtered MailMessage objects

SendMail

Sends a list of MailMessage objects

Note: This requires Admin privileges

Update

Updates an existing MailMessage object

Note: Uses the MailUpdate to define the operation

Here are API highlights for MailMessage.

This is the core structure of MailMail - A message sent from a player to a player messages.

Parameter Name

Detail

id

The unique ID of the MailMail - A message sent from a player to a player message

sent

The timestamp when sent

Note: This value is formatted as 2019-03-28T00:00:00Z

receiverGamerTag

Receiver DBIDDBID - The database identification. Beamable generates an anonymous account for the player when the project first runs

senderGamerTag

Sender DBIDDBID - The database identification. Beamable generates an anonymous account for the player when the project first runs

category

Arbitrary category string

subject

The subject of the mail

body

The main content (in text) of the mail

state

"unread", "read", or "deleted"

expires

The timestamp when expires

Note: This value is formatted as 2019-03-28T00:00:00Z

Examples

Here are examples which cover common programming needs.

📘

Beamable SDK Examples

This and all examples are available for download at GitHub.com/Beamable_SDK_Examples

In this MailServiceExample the tbd...

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Beamable.Common.Api;
using Beamable.Common.Api.Mail;
using Beamable.Examples.Shared;
using UnityEngine;
using UnityEngine.Events;

namespace Beamable.Examples.Services.MailService
{
   /// <summary>
   /// Holds data for use in the <see cref="MailServiceExampleUI"/>.
   /// </summary>
   [System.Serializable]
   public class MailServiceExampleData
   {
      public long Dbid = 0;
      public int UnreadMailCount = 0;
      
      // UI messages that indicate mail exists or not
      public List<string> UnreadMailLogs = new List<string>();
      public List<string> UpdateMailLogs = new List<string>();
      public List<string> SendMailMessageLogs = new List<string>();
      public List<string> MailMessageLogs = new List<string>();
      
   }
   
   [System.Serializable]
   public class RefreshedUnityEvent : UnityEvent<MailServiceExampleData> { }
   
   /// <summary>
   /// Demonstrates <see cref="MailService"/>.
   /// </summary>
   public class MailServiceExample : MonoBehaviour
   {
      //  Events  ---------------------------------------
      [HideInInspector]
      public RefreshedUnityEvent OnRefreshed = new RefreshedUnityEvent();
      
      
      //  Fields  ---------------------------------------
      private IBeamableAPI _beamableAPI;
      private MailServiceExampleData _data = new MailServiceExampleData();
      private const string MailCategory = "";

      
      //  Unity Methods  --------------------------------
      protected void Start()
      {
         string startLog = $"Start() Instructions..." +
                           $"\n * Play Scene" +
                           $"\n * Check for mail using UI. Probably none" +
                           $"\n * Stop Scene" +
                           $"\n * Unity → Window → Beamable → Examples → MailService → Send Test Mail To Active User" +
                           $"\n * Play Scene" +
                           $"\n * Check for mail using UI. Probably some\n\n";
         
         Debug.Log(startLog);

         Refresh();
         SetupBeamable();
      }

      
      //  Methods  --------------------------------------
      private async void SetupBeamable()
      { 
         _beamableAPI = await Beamable.API.Instance;

         _data.Dbid = _beamableAPI.User.id;
         Debug.Log($"beamableAPI.User.id = {_data.Dbid}");

         // Fetch All Mail
         _beamableAPI.MailService.Subscribe(async mailQueryResponse =>
         {
            _data.UnreadMailLogs.Clear();
            _data.UnreadMailCount = mailQueryResponse.unreadCount;
            string unreadMailLog = $"unreadCount = {_data.UnreadMailCount}";
            _data.UnreadMailLogs.Add(unreadMailLog);

            await GetMail();
            Refresh();
         });

         Refresh();
      }

      
      private async Task<EmptyResponse> GetMail()
      {
         _data.MailMessageLogs.Clear();
         var listMailResponse = await _beamableAPI.MailService.GetMail(MailCategory);
         foreach (var mailMessage in listMailResponse.result)
         {
            string mailMessageLog = $"MailMessage" +
                                    $"\n\tname = {mailMessage.senderGamerTag}" +
                                    $"\n\tname = {mailMessage.receiverGamerTag}" +
                                    $"\n\tname = {mailMessage.subject}" +
                                    $"\n\tname = {mailMessage.body}" +
                                    $"\n";
            _data.MailMessageLogs.Add(mailMessageLog);
         }
         
         Refresh();

         return new EmptyResponse();
      }

      
      public async void UpdateMail()
      {
         _data.UpdateMailLogs.Clear();
         var mailUpdateRequest = new MailUpdateRequest();
         
         // Arbitrary Example - Toggle "read" to "unread"
         var listMailResponse = await _beamableAPI.MailService.GetMail(MailCategory);
         foreach (var mailMessage in listMailResponse.result)
         {
            MailState newMailState = MailState.Read;
            if (mailMessage.MailState == MailState.Read)
            {
               newMailState = MailState.Unread;
            }
            mailUpdateRequest.Add(mailMessage.id, newMailState, true, mailMessage.expires);
         }
    
         await _beamableAPI.MailService.Update(mailUpdateRequest);
         
         string updateMailLog = $"updateMailRequests = {mailUpdateRequest.updateMailRequests.Count}";
         _data.UpdateMailLogs.Add(updateMailLog);
         
         Refresh();
      }
      
      
      public void ResetUserProgress()
      {
         ExampleProjectHacks.ClearDeviceUsersAndReloadScene();
      }

      
      public void Refresh()
      {
         string refreshLog = $"Refresh() ...\n" +
                             $"\n * UnreadMailCount.Count = {_data.UnreadMailCount}" +
                             $"\n * UnreadMailLogs.Count = {_data.UnreadMailLogs.Count}" +
                             $"\n * SendMailMessageLogs.Count = {_data.SendMailMessageLogs.Count}" +
                             $"\n * MailMessageLogs.Count = {_data.MailMessageLogs.Count}\n\n";
         Debug.Log(refreshLog);
         
         // Send relevant data to the UI for rendering
         OnRefreshed?.Invoke(_data);
      }
      
      
      /// <summary>
      /// NOTE: This must be 1. called at runtime from a user with
      /// admin privileges or 2. called at edit-time from any user
      ///
      /// For this demo, #2 is used.
      /// 
      /// </summary>
      public static async void SendMailMessage()
      {
         if (Application.isPlaying)
         {
            Debug.Log ($"SendMailMessage() Failed. Must call at edit-time.");
            return;
         }
         
         IBeamableAPI beamableAPIFromStatic = await Beamable.API.Instance;
         long userId = beamableAPIFromStatic.User.id;
      
         // Arbitrary Example - Send mail from ME to ME 
         var mailSendRequest = new MailSendRequest();
         var mailSendEntry = new MailSendEntry();
         mailSendEntry.category = MailCategory;
         mailSendEntry.senderGamerTag = userId;
         mailSendEntry.receiverGamerTag = userId;
         mailSendEntry.body = $"Test Mail Body From {userId}.";
         mailSendEntry.subject = $"Test Mail Subject From {userId}.";
         mailSendRequest.Add(mailSendEntry);

         // Call may fail if sender lacks permissions
         bool isSuccess = true;
         try
         {
            var emptyResponse = await beamableAPIFromStatic.MailService.SendMail(mailSendRequest);
         }
         catch (Exception e)
         {
            Debug.LogError(e.Message);
            isSuccess = false;
         }

         if (isSuccess)
         {
            Debug.Log ($"SendMailMessage() Success!");
         }
      }
   }
}

Advanced

This section contains any advanced configuration options and workflows.

Mobile Notifications

Mobile Notifications are a native part of mobile platforms including iOS and Android. These messages show up as a banner of text, regardless if your game is running.

See Notifications for more info.


Did this page help you?