MandrillEmailManager.cs 2.87 KB
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WebKit;

public class MandrillEmailManager : Singleton<MandrillEmailManager>
{
    [SerializeField]
    private string _mandrillKey;
    [SerializeField]
    private string _mandrilTemplate;

    private void Awake()
    {
        if (MandrillEmailManager.Instance != null && MandrillEmailManager.Instance != this)
        {
            Destroy(this.gameObject);
            return;
        }

        WebRequest.cacheRequests = true;
    }

    private const string mandrilUrl = "https://mandrillapp.com/api/1.0/messages/send-template.json";
    private Queue<Request> _requests = new Queue<Request>();

    public void SendEmail(string emailAddress, Dictionary<string, object> args)
    {
        var formattedContent = new List<Dictionary<string,object>>();
        foreach(KeyValuePair<string,object> kvp in args)
        {
            var newDict = new Dictionary<string, object>()
            {
                { "name", kvp.Key },
                { "content", kvp.Value }
            };

            formattedContent.Add(newDict);
        }

        var payload = new Dictionary<string, object>()
        {
            { "key", _mandrillKey },
            { "template_name",  _mandrilTemplate },
            { "template_content", "" },
            { "async", false },
            {
                "message", new Dictionary<string,object>()
                {
                    {
                        "merge_language", "handlebars"
                    },
                    {
                        "to", new List<Dictionary<string, object>>()
                        {
                            new Dictionary<string, object>()
                            {
                                { "email", emailAddress },
                                { "type", "to" }
                            }
                        }
                    },

                    { "global_merge_vars", formattedContent }
                }
            }
        };

        print(MiniJSON.Json.Serialize(payload));

        //Request req = new Request()
        //{
        //    method = RequestMethod.POST,
        //    url = mandrilUrl,
        //    data = payload,
        //    onComplete = EmailSendComplete
        //};

        //req.Send();

        StartCoroutine(SendMandrillEmail(payload));
    }

    private IEnumerator SendMandrillEmail(object payload)
    {
        byte[] data = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(payload));
        WWW thisReq = new WWW(mandrilUrl, data);

        yield return thisReq;

        print(thisReq.text);
    }

    private void EmailSendComplete(Response resp)
    {
        if(!string.IsNullOrEmpty(resp.error))
            Debug.LogError("Error with mail request - " + resp.error);
        else
            Debug.Log("Email sent " + resp.text);
    }
}