UnityThere’s a huge opportunity for email games, as I wrote in a previous post. There’s also a need for email within games. Unity is a popular tool for publishing multi-platform games. But what about sending email from Unity? I decided to share how I did this with SendGrid.

When you’re developing in Unity you can use either C#, Javascript, or Boo. I’m going to show an example using C# to send email through SMTP using SendGrid’s SMTP API and by making a simple HTTP request using the Web API.

First, to send using SMTP is really simple. You can use the System.Net.Mail library to use the MailMessage and SmtpClient classes:

MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromEmail);
mail.Subject = subject;
mail.Body = body;
mail.Headers.Add("X-SMTPAPI", xsmtpapiJSON);

SmtpClient smtpServer = new SmtpClient("smtp.sendgrid.net");
smtpServer.Port = 587;
smtpServer.Credentials = new System.Net.NetworkCredential(api_user, api_key) as ICredentialsByHost;
smtpServer.EnableSsl = true;
ServicePointManager.ServerCertificateValidationCallback = 
  delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 
      { return true; };
Debug.Log("Success, email sent through SMTP!");

To use SendGrid’s SMTP API all you have to do is use one line of code:
mail.Headers.Add("X-SMTPAPI", "{\"category\":\"game_email\"}");

Now to send using the Web API is even simpler. All you have to do is make a simple HTTP request:

public void SendSendgridEmailWebAPI () {
  string url = "https://sendgrid.com/api/mail.send.json?";
  url += "to=" + toEmail;
  url += "&from=" + fromEmail;
  //you have to change every instance of space to %20 or you'll get a 400 error
  string subjectWithoutSpace = subject.Replace(" ", "%20");
  url += "&subject=" + subjectWithoutSpace;
  string bodyWithoutSpace = body.Replace(" ", "%20");
  url += "&text=" + bodyWithoutSpace;
  url += "&x-smtpapi=" + xsmtpapiJSON;
  url += "&api_user=" + api_user;
  url += "&api_key=" + api_key;
  WWW www = new WWW(url);

IEnumerator WaitForRequest(WWW www)
  yield return www;

  // check for errors
  if (www.error == null)
      Debug.Log("WWW Ok! Email sent through Web API: " + www.text);
  } else {
      Debug.Log("WWW Error: "+ www.error);

As with SMTP, using the SMTP API with the Web API only takes one line:
url += "&x-smtpapi=" + xsmtpapiJSON;

I created a sample project with two buttons, clicking one them will send an email either using SMTP, or the Web API.

One way to make use of email inside your game could be, for example, tracking how much time the user spends playing with a character, and sending him an email with a desktop screenshot of it. Or sending an email with a nice screenshot the moment the player gets an achievement.

How else do you think emails could be useful inside a game?

Heitor is a Developer Evangelist at SendGrid based in Sao Paulo, Brazil. Passionate about hackathons, games and entrepeneurship.