How to Send an Email or Text Message in C# with Unity

Поділитися
Вставка
  • Опубліковано 5 лют 2025
  • In this video, I'll show you how to send emails and text messages in your c# app with unity. You can do this on mobile or on PC with the exact same code. See below for referenced code.
    using UnityEngine;
    using UnityEngine.UI;
    using System.Net;
    using System.Net.Mail;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    public class EmailFactory : MonoBehaviour
    {
    public InputField bodyMessage;
    public InputField recipientEmail;
    public void SendEmail()
    {
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    SmtpServer.Timeout = 10000;
    SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
    SmtpServer.UseDefaultCredentials = false;
    SmtpServer.Port = 587;
    mail.From = new MailAddress("myEmail@gmail.com");
    mail.To.Add(new MailAddress(recipientEmail.text));
    mail.Subject = "Test Email through C Sharp App";
    mail.Body = bodyMessage.text;
    SmtpServer.Credentials = new System.Net.NetworkCredential("myEmail@gmail.com", "MyPasswordGoesHere") as ICredentialsByHost; SmtpServer.EnableSsl = true;
    ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
    return true;
    };
    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
    SmtpServer.Send(mail);
    }
    public void SendText(string phoneNumber)
    {
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    SmtpServer.Timeout = 10000;
    SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
    SmtpServer.UseDefaultCredentials = false;
    mail.From = new MailAddress("myEmail@gmail.com");
    mail.To.Add(new MailAddress(phoneNumber + "@txt.att.net"));//See carrier destinations below
    //message.To.Add(new MailAddress("5551234568@txt.att.net"));
    mail.To.Add(new MailAddress(phoneNumber + "@vtext.com"));
    mail.To.Add(new MailAddress(phoneNumber + "@messaging.sprintpcs.com"));
    mail.To.Add(new MailAddress(phoneNumber + "@tmomail.net"));
    mail.To.Add(new MailAddress(phoneNumber + "@vmobl.com"));
    mail.To.Add(new MailAddress(phoneNumber + "@messaging.nextel.com"));
    mail.To.Add(new MailAddress(phoneNumber + "@myboostmobile.com"));
    mail.To.Add(new MailAddress(phoneNumber + "@message.alltel.com"));
    mail.To.Add(new MailAddress(phoneNumber + "@mms.ee.co.uk"));
    mail.Subject = "Subject";
    mail.Body = "";
    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("myEmail@gmail.com", "MyPasswordGoesHere") as ICredentialsByHost; SmtpServer.EnableSsl = true;
    ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
    return true;
    };
    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
    SmtpServer.Send(mail);
    }
    }

КОМЕНТАРІ • 97

  • @jayantbarthwal4470
    @jayantbarthwal4470 3 роки тому +3

    Hi i got an error: SmtpException: 535-5.7.8 Username and Password not accepted
    my email and password are correct and google also send me a msg that a third party app is trying to access your gmail and i said 'Yes it was me' but still it's not sending msg , i think i have to change some setting in gmail for allowing access , but i don't know what to do. please help

    • @wolfscrygames
      @wolfscrygames  3 роки тому +3

      Hello, there's a setting in gmail to allow a 3rd party app. support.google.com/accounts/answer/3466521?hl=en
      You'll have to enable 3rd party access for your app to work with gmail.

    • @wolfscrygames
      @wolfscrygames  3 роки тому +5

      myaccount.google.com/lesssecureapps this is the direct link to the setting you need to change

    • @jayantbarthwal4470
      @jayantbarthwal4470 3 роки тому +2

      @@wolfscrygames Thank you so much for this direct link , now email sends perfectly

    • @Dweeh
      @Dweeh 2 роки тому +2

      @@wolfscrygames When I tried to do this - there was a message saying that this setting will be depracated May 30 2022.
      I guess this will not work after that date..?

    • @marshallb1656
      @marshallb1656 2 роки тому

      @@Dweeh This video will help with setting up two step authentication and a random pw. ua-cam.com/video/IWxwWFTlTUQ/v-deo.html

  • @RobertGercia
    @RobertGercia 2 роки тому

    It's 2022. This tutorial remain as one of recommended video. Thanks for the great work!

  • @jasperIM
    @jasperIM Рік тому

    It's 2024. This method still works. Thanks for your video~

    • @rafikyasser4288
      @rafikyasser4288 8 місяців тому

      it did not work with me. google refuses to work.

  • @hamnamahboob7894
    @hamnamahboob7894 3 роки тому +2

    Thanks for Amazing and very helpful tutorial. it saves a lot of my time. 1 question I just want to ask what code we should add if the email is successfully send or not?

  • @lgknmerp
    @lgknmerp 2 роки тому +3

    This tutorial works fine for me. But now Google stopped the less secure apps, so the email from unity apps wont be send. Any alt email for that purpose ?

  • @emrelatos
    @emrelatos 2 роки тому

    i tried my carrier destination of my country but is not working

  • @kawerishirke5568
    @kawerishirke5568 4 роки тому +2

    Amazing tutorial, thank you so much, very very very helpful for me, thank you so much. .. 🙏👍👍

  • @danjayson1
    @danjayson1 5 років тому +4

    Thank you for the tutorial Dr.Strange :D

  • @MegaJHONDY
    @MegaJHONDY 2 роки тому +2

    thanks dude, you rock!

  • @emrelatos
    @emrelatos 2 роки тому

    hello man am suffering with text messege can you help me adress not found

  • @ykblue999
    @ykblue999 2 роки тому +1

    Thanks a lot. So easy. You made my day.

  • @danielcorzo7498
    @danielcorzo7498 3 роки тому +1

    Hi, great tutorial! Can you do a video on Authentication? Something like OAuth? I want the users to be able to send emails with their accounts from my app.

  • @HarishS-k3w
    @HarishS-k3w Рік тому

    Does this work on unity WebGL builds? please reply fast!

  • @davidmason7519
    @davidmason7519 4 роки тому +1

    amazing and very helpful tutorial thank you very much!!!!

  • @lukedraper6313
    @lukedraper6313 5 років тому +2

    Thanks for the tutorial. Just wanted to ask what the code line is if you have a fixed email to send the emails to. So eliminating the email input field and have the email sent to a predetermined address.

    • @wolfscrygames
      @wolfscrygames  5 років тому +1

      Instead of using the recipientemail.text, you can assign a string. This will be the mail.To.Add(new MailAddress(toAddress@yahoo.com));

  • @d1a9n8a8
    @d1a9n8a8 3 роки тому

    it works amazing, thank you!

  • @isly7537
    @isly7537 3 роки тому

    Thank you for your video !

  • @jrricky
    @jrricky 3 роки тому

    Doesn't work for me. Unity freezes for like a minute after I click the button and then I get error: "IOException: Connection closed
    System.Net.Mail.SmtpClient.Read () "

  • @Eculeus007
    @Eculeus007 3 роки тому

    Thanks for your great Tut! How can i receive emails in to unity?

  • @darkman237
    @darkman237 2 роки тому

    Would this still work on a desktop build?

  • @leannemerritt2361
    @leannemerritt2361 2 роки тому +1

    Thanks for making this tutorial! I'm having a problem with the text input and wonder if anyone can help. It works well if I type the recipient email address directly into the the editor or as a string in the script but it doesn't work when I use the input field. I get the error SmtpFailedRecipientsException: failed recipients. Entering text into the input field seems to be working normally. Anyone else have the same problem or have an idea of what I'm missing?

    • @wolfscrygames
      @wolfscrygames  2 роки тому +1

      Hello,
      There's a weird behavior with input fields that are too small where it cuts off the end of the string. Try making the text area larger and see how that goes.

    • @leannemerritt2361
      @leannemerritt2361 2 роки тому

      @@wolfscrygames Wow, thanks for the fast response! I tried making the input field bigger but it doesn't seem to make a difference. I added a line to copy what I have in the input box to the console and everything seems to be correct.

  • @gainplaystudio8557
    @gainplaystudio8557 10 місяців тому

    Unfortunately "This setting is not available for your account."

  • @jhonuribe171
    @jhonuribe171 2 роки тому +2

    Me costo trabajo porque ahora cambiaron la seguridad de gmail, Nota: utiliza el mismo usuario y copia la contraseña. Aquí te dejo un link para que veas de como modificarlo ua-cam.com/video/yuT6PhH-5iw/v-deo.html y para el bro que subio este video bendito sea joven, desde colombia. Another programmer.

  • @flightsimguy3897
    @flightsimguy3897 2 роки тому

    For webgl it is not working help

  • @kiddoryandee6714
    @kiddoryandee6714 4 роки тому +1

    how about a button with values that when clicked, the btn will send message to a phone number,,, meaning that the message is fixed and stored in the button itself? will it work?

    • @wolfscrygames
      @wolfscrygames  4 роки тому

      Yes, this will work, but you'd preferably need to know the user's carrier otherwise if you brute force it most of the emails get a failed to send

    • @kiddoryandee6714
      @kiddoryandee6714 4 роки тому +1

      @@wolfscrygames im still stuck with this process, do you know how to code it so this will work?

    • @kiddoryandee6714
      @kiddoryandee6714 4 роки тому +1

      @@wolfscrygames or make a tutorial for this issue

    • @wolfscrygames
      @wolfscrygames  4 роки тому

      @@kiddoryandee6714 you need to write a method with the fixed values you need. Then, assign that method to the button. The email you send it to depends on the carrier. If you have your own mail server, you can try sending it to all carriers without checking, but I'm not sure if that has any long term effects from the receiving end.

  • @jeanb.3967
    @jeanb.3967 3 роки тому

    I did all that is on the tutorial, yet when i click it does not send any email to my designated mail. There are also no errors in the console. Help?

    • @jeanb.3967
      @jeanb.3967 3 роки тому

      I also have the less secure apps access on. I dont know what to do further.

  •  4 роки тому +1

    Hello, I have a problem. It works through Unity editor when I play the game, but when I build the project for PC and play again (out of Unity) it stops working. I would appreciate if you could help me. Thanks!

    •  4 роки тому

      I eventually got same result by creating a form and capturing the information through a php file hosted on a server which will send all the information to my email.

    • @AfterFashion-gmjp4
      @AfterFashion-gmjp4 4 роки тому

      Try to enable internet access from auto to require.
      You can find it under player setting->other settings.

  • @vltStylish
    @vltStylish 4 роки тому +1

    hey i am getting this error could you tell me what i could be doing wrong :
    NullReferenceException: Object reference not set to an instance of an object EmailFactory.SendEmail() (at Assets/EmailFactory.cs:23)
    Line 23 is : mail.To.Add(new MailAddress(recipientEmail.text));
    Any ideas why its giving me this error just to reduce the error i did everything the same as you did used the same names and everything still this is a persistent error for me

    • @wolfscrygames
      @wolfscrygames  4 роки тому +1

      Seems like your recipient email string is null. This could be due to you not dragging the text gameObject into the slot in the editor.

    • @vltStylish
      @vltStylish 4 роки тому

      @@wolfscrygames could you take anydesk for a bit and see what i could be doing wrong i am fairly new to unity and visual studio *basically a noob* Anydesk

    • @vltStylish
      @vltStylish 4 роки тому +1

      @@wolfscrygames It was a really big help i never though i would get it to work i am really grateful that i came to your channel Thank you a million times i have been banging my head with this for 2 days and since i didnt know unity i had no idea that i had to drag and drop the textfields :) *Thumbs Up*

  • @geoffreyhendrikx
    @geoffreyhendrikx 3 роки тому

    Do you make a tutorial about how to send email with a more secure custom server?

    • @wolfscrygames
      @wolfscrygames  3 роки тому

      If you have a custom server, I believe you would just need to update the server address. Instead of smtp.gmail.com, you would use your email server's address.

  • @barisde1634
    @barisde1634 3 роки тому

    Hi does the sending of the email also work under VR-Platform - Oculus Quest...

    • @wolfscrygames
      @wolfscrygames  3 роки тому

      Hello,
      Since it's C# based, yes, it works in any environment as long as internet connection is available. If a quest 1 is being used, or quest for business, it's not accurate to assume the user is connected. Quest 2 has a reasonable assumption of internet connectivity since Facebook login is required.

  • @nikolahunter7
    @nikolahunter7 2 роки тому

    Hi I got this error: FormatException: The specified string is not in the form required for an e-mail address.
    System.Net.Mail.MailAddress.ParseAddress (System.String address) (at :0). This error pops out when I click on "Send" button

  • @queriesask1765
    @queriesask1765 3 роки тому

    Hi, Thank you so much for the tutorial. I have followed your tutorial to send an email for my Unity Pc application.
    I am getting the following Exception while sending email request :
    SmtpException: Server does not support secure connections.
    I have enabled Less secure app access permission in my Gmail settings.
    Can you please provide a solution for this exception.
    Thank you.

    • @wolfscrygames
      @wolfscrygames  3 роки тому

      Hello,
      Unfortunately, I don't have a solution for that issue other than suggesting you host a mail server of your own. There may be regional differences, or updates as time progresses, that cause this code to have different requirements.

    • @queriesask1765
      @queriesask1765 3 роки тому

      @@wolfscrygames Thank you very much! Is there any other alternative way to send emails from Unity.

  • @GrafitiGames
    @GrafitiGames 4 роки тому

    Really nice tutorial i love it!!! one question, can you Sent one email with more bodys, Like Name: + Last Name: + Hobbys:

    • @wolfscrygames
      @wolfscrygames  4 роки тому

      Sorry for the late reply, I don't get notifications sometimes (rather often actually). You can combine multiple variables into one string, then use that for the body. I'm sure you already figured that out, but just in case, I figured I'd drop a comment.

    • @wolfscrygames
      @wolfscrygames  4 роки тому

      @@DGoncerz yes, if you have multiple string variables, you can simply add them.
      string firstString = "chocolate";
      string secondString = "covered";
      string sum = firstString + secondString;
      At this point, sum is "chocolatecovered"

  • @burakgulrmak7085
    @burakgulrmak7085 Рік тому

    it doesn't work anymore :(

  • @ajgm1919
    @ajgm1919 4 роки тому

    How could it be done that instead of sending the email or message, just open the mobile application, the telephone keyboard or the WhatsApp application through a button with some default data, it would be for a business card in augmented reality, made with Unity 3d and vuforia. Thanks in advance for your help and best regards.

    • @wolfscrygames
      @wolfscrygames  4 роки тому

      You have to look into the documentation for each operating system to open applications. It'll be different on ios and on Android.

  • @AGeek
    @AGeek 4 роки тому

    Hello when i running it in editor everthing works fine but when i use Build & Run option and it opens in broswer(Chrome) it doesnt sends the mail and gives my socketexception Please Help

    • @wolfscrygames
      @wolfscrygames  4 роки тому +1

      Hello,
      WebGL builds do not retain full functionality like standalone builds. Every browser and every operating system will handle them differently and many features are lost. This is the extent of my knowledge on the solution to your issue. I'd advise finding a website based solution.

    • @AGeek
      @AGeek 4 роки тому

      @@wolfscrygames
      i found this written in a forum this Wink00 says : "You can have Unity WebGL call a javascript function which then calls PHP and send the email." but i dont understand what he means by it

    • @wolfscrygames
      @wolfscrygames  4 роки тому +2

      @@AGeek it means you can use a traditional method for sending an email on a website. PHP is a bit more secure than html. Sockets probably wont work.

    • @AGeek
      @AGeek 4 роки тому

      @@wolfscrygames i worked last 6 hours and created a WebAPI to send emails and used that with the unity and it works great in editor but i am getting different error in browser i have sent you debug.txt file on your discord could you please take a look and tell my what i might be doing wrong?

    • @vltStylish
      @vltStylish 4 роки тому

      @@wolfscrygames both are my ids i am the same person ageek please take a look in discord

  • @icme9287
    @icme9287 Рік тому

    ty

  • @ma.dianadeguia6985
    @ma.dianadeguia6985 2 роки тому

    Are u real or fake because i play ur games and theres a lot of advertisement how come that when i log in ur games to claim my reward i cannot open the games

  • @acursedhope
    @acursedhope 4 роки тому

    I get the error: "server does not support secure connections" any ideas on how to fix this?

    • @wolfscrygames
      @wolfscrygames  4 роки тому

      I was able to get it to work using a Google email and changing the settings on gmail. It should also work with a custom email if you have your own server.

    • @acursedhope
      @acursedhope 4 роки тому +1

      @@wolfscrygames ok thank you! great tutorial btw

    • @wolfscrygames
      @wolfscrygames  4 роки тому

      @@acursedhope thanks, hope it helps

  • @abudriaz9678
    @abudriaz9678 2 роки тому

    how to send email to all the email address at same time not just particular one like this video its gmail how to make it work for all mail addresses at same time like google yahooo hotmail etc..

    • @wolfscrygames
      @wolfscrygames  2 роки тому +1

      I think you misunderstand. This one just shows gmail as a "from" address, but you can send to multiple addresses. You may want to look into loops and lists to learn how to work with more than one item at a time.

    • @abudriaz9678
      @abudriaz9678 2 роки тому

      @@wolfscrygames ya sorry my bad i misunderstood this i tryed it in my project and it worked great thanks for the video now i am thinking of trying to send mail from my own custom server not gmail yahoo etc ...

    • @abudriaz9678
      @abudriaz9678 2 роки тому +1

      @@wolfscrygames i want to use this method to generate random code and send it to the user's email for verification of email address is this practice good for this approach is it a secure way?

    • @wolfscrygames
      @wolfscrygames  2 роки тому +1

      I've seen confirmation codes and links sent in emails. Both methods are prevalent and fairly effective at validating email addresses.
      As long as your email does NOT prompt any sort of login, and does not lead users to a webpage where they may login, it's fine.
      An email link, when used, should make an http request. It should not resemble phishing in any way.

    • @abudriaz9678
      @abudriaz9678 2 роки тому

      @@wolfscrygames ok got it once again thanks for reply !

  • @PoulBox
    @PoulBox 2 роки тому

    Not working , because Gmail disabled less secure system for more security 🤦

    • @itamar300893
      @itamar300893 2 роки тому

      Hi, did you figured it out by any chance?

  • @ma.dianadeguia6985
    @ma.dianadeguia6985 2 роки тому

    Are u real o fake