MATTHEW VENTURES
  • Home
  • Resume
  • Side Quests
  • Other
    • Professional Timeline
    • Recommendations
    • Tutorials
    • Research >
      • Glyph
      • NASA
    • Getting Into Game Dev

Sending Emails From Your Unity Game

8/14/2019

12 Comments

 
Have you ever wanted to send emails from your Unity Indie Game? This tutorial covers two ways including direct emails, through the C# .Net, and forwarding the message through a server-hosted php script.​
Update (June 3, 2021):
Hey it's me, from the FUTURE! I would no longer recommend these methods expect in one special case where you do not want to show the user that you're sending an email (secret email). If it's okay to show the user the email, and allow them to send it from their personal address, I would advise an alternative approach: https://pastebin.com/EKHsvWNQ (also uploaded below if this link dies).
emailaddendum.cs
File Size: 1 kb
File Type: cs
Download File

Introduction / Motivation
Here are some reasons why you might consider sending emails from your game:
- Setup two-factor authentication
- Enable players to give you feedback or bug reports
- Secretly record error messages, crash logs, or suspicious player activity

For these purposes and more, we shall explore two methods of sending an email...

Overview of "Method 1: Direct message"
This method will require us to setup a Gmail account from which we can send an email using .Net libraries. This is the best, fastest, method for sending emails. However, this method will not work on games that are hosted online such as the WebGL target platform (for example a game hosted in-browser on itch.io).

Overview of "Method 2: Server request"
This method involves sending an email to a server script which can then forward our data to the destination address. This is a slower method and we face a greater risk of Gmail labeling our messages as spam. However, this method will work on all platforms.

Setup
I have created a simple Unity scene for testing which includes an input field, a button, and the script we will be writing. The script has the text of the input field and the button linked to it as Serialized Fields. There is also a checkbox we can toggle to switch between methods of delivery.
Picture

​Implementing "Method 1: Direct message"
First we need to create a Gmail account. I highly recommend creating a new one explicitly for this purpose because we will need to include both the username and password of this account in the source code. A naughty hacker could, in theory, get access to the code so please be careful what you include there.

With our Gmail setup, we can now start defining the code for our Emailer.cs file. Some code is preceeded by the comment "Method 2" to let you know it will not be needed for this first approach. Mind the import statements here which include the .Net libraries we will need to verify our email credentials. Of course, make sure you replace my email credentials with yours.

By using the .Net support for emailing along with the Gmail we created, the above method SendAnEmail will reliably get our message where it needs to go! However, a limitation of this method is that it will not work on WebGL games. For these cases, we need to consider an alternative approach.

​Implementing "Method 2: Server request"
Method 2 will allow us to send a WWW request to a server-hosted php script that can forward our data. While it is not as fast or reliable as Method 1, it does work on all platforms! The C# side of this approach is included in the code of Emailer.cs (above) and includes creating a WWWForm with the data we want to send, then forwarding it to our server. With that aspect completed, all that is left for us to do is create and host our server script! Let's setup the hosting first.
​I used the free hosting website 
https://www.000webhost.com.
Using 000webhost
If you choose to use their hosting services as well, select the "Create a new Site" button on their "My Sites" page. Record the website name and password somewhere safe!
Then look inside the "Create new website" options for a "Upload own website" button. From there you can select "New File", and later "Edit", on the top right toolbar to create your server script.
Picture
Once you have a server host setup you can use the code of "Emailer.php" (below) to receive the form we sent from our C# code. This code ensures that it is receiving a form with the necessary data before sending an email. The headers include data which is meant to suppress Gmail's spam filters allowing your message to reach an inbox as desired (however in my test, it did get stuck in a spam folder at first).

These are only two of many approaches you may consider for sending emails in your games. Please consider "liking" this post or commenting on which aspects were most helpful / confusing. Your readership is very much appreciated!
12 Comments
Luke link
11/7/2019 09:09:20 pm

Hey!!! Thanks a lot for the tutorial. Just wanted to check. Can I send the information via email if it's from UI Text input fields?

using System.Collections;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using UnityEngine.UI;

public class Emailer : MonoBehaviour
{

public InputField dateText;
public InputField classText;
public InputField informationText;

[SerializeField] TMPro.TextMeshProUGUI txtData;
[SerializeField] UnityEngine.UI.Button btnSubmit;
[SerializeField] bool sendDirect;

const string kSenderEmailAddress = "SenderEmail";
const string kSenderPassword = "SenderPassword";
const string kReceiverEmailAddress = "ReceiverEmail" ;


private static void SendAnEmail(string message)
{

MailMessage mail = new MailMessage();
mail.From = new MailAddress(kSenderEmailAddress);
mail.To.Add(kReceiverEmailAddress);
mail.Subject = "Swift Report Demo";
mail.Body = message;

}
}


Any idea what I'm missing? Thanks so much :)

Reply
Matthew Ventures
6/3/2021 11:42:44 pm

Yes of course, just add the input field text to the message string. Something like "message += classText.text"

Reply
Scott Vander Pryt
1/9/2020 04:25:01 pm

Hey their, great tutorial. I'm trying to use this for a school project were going to publish. I was wondering if you know how to deal with the fact that gmail is telling me (a outside source thats not google is attempting to send a email through your account, this has been avoided).

As results in the program I get:
-Username & Password not accepted
-Email sent succesfully (but it wasnt)

Reply
Matthew Ventures
6/3/2021 11:41:45 pm

I would advise this approach:
https://pastebin.com/EKHsvWNQ

Reply
Steven
1/11/2020 06:23:45 pm

Well written, thanks!

Reply
Okuse Marvellous link
3/11/2021 11:16:36 am

Amazing article, the way this <a href="https://www.techfiver.com/gmail-2021-account-create/">post was arranged is so wonderful</a> and I have never seen any website that his or her website is arranged just like yours. Thanks, for the review and for making it available for us on Google.

Reply
Walid Babi
6/2/2021 08:05:33 am

hi thanks for the guide , i am getting
-Username & Password not accepted
-Email sent succesfully (but it wasnt)
and with second method no errors but the email is never sent

Reply
Matthew Ventures
6/3/2021 11:41:12 pm

I'm sorry to hear that. I would advise an alternative approach:
https://pastebin.com/EKHsvWNQ

Reply
Ruawl
8/17/2021 06:26:24 pm

Hi there, thanks for the tutorial!

Im building this WebGL application where user can change some indexes through UI inputs. Then those indexes are used to build a "path" string that loads an image to scenery background using 'Resources.Load("path")'.

I need to know which image was chosen by each user but, to get this simplified, knowing the chosen 'path' string (or even chosen indexes) would be enough for now.

So i was trying to send an email following your fake account hint with such "path" string as body message, and first method works fine testing from Unity editor. But since mine its a WebGL application, i needed the second method to make it work.

I got nothing at first, then i replaced WWW with UnityWebRequest, and right now im able to reach the 'if($success)' condition displaying its confirmation message.

But the email never arrives (even at Spam folder) and i wasn't able to find a solution so far. Do you have any ideas bout why this is happening? Or even an alternative solution i could adopt to this?

(I kinda need a way to send an email/sms/anything silently (as a own feedback) with some string as body message without opening any windows 'like mailto approach', so that second method looked perfect on your YouTube Vid, but it's not working so far =/)

Sorry bout the long post, thanks in advance for any feedback!

Reply
Matthew Ventures
8/17/2021 08:31:59 pm

Thanks for reading. I think we need to evaluate if another form of data collection could work here. I wrote this guide a few years ago and the spam practices are increasingly stringent so it's really hard to get something like this working over email. I would do it this way if you want to use google: https://www.youtube.com/watch?v=fPfH8ZLcrmY&t=1s&ab_channel=MatthewVentures
Otherwise a traditional database works well too such as firebase.

Reply
Dennis
10/25/2022 08:11:32 pm

Does not work

June 3, 2021 update is broken code

as May 2022 Goggle change things that the first Method will not work

Reply
Matthew
10/26/2022 12:07:21 am

Hey, thanks for checking it out. Yes it would seem that Google's spam filtering has become absolutely draconic recently and unless you're sending email through an approved company, it's just not going to get through. So I think ultimately that first option is no longer available and you're going to have to explore the other options.

Reply



Leave a Reply.

  • Home
  • Resume
  • Side Quests
  • Other
    • Professional Timeline
    • Recommendations
    • Tutorials
    • Research >
      • Glyph
      • NASA
    • Getting Into Game Dev