Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
6
Question by sdgd · Apr 07, 2013 at 11:08 AM · c#how-toemailsendoafa

How To send Email with C# on Unity 3D 4.1.2?

first I came across this article:

Dave On C# Programming tutorials

I got few errors and I start searching:

Unity 3 - Sending Email with C#

but I just cannot figure out how to solve this:

 using UnityEngine;
 using System.Net;
 using System.Net.Mail;
 using System.Collections;
 
 public class SendEmail : MonoBehaviour {
     void Start () {
         Debug.Log("asdgf");
         SendEmailF();
         
     }
     private void SendEmailF(){
         // Create a System.Net.Mail.MailMessage object
         MailMessage message = new MailMessage();
         
         // Add a recipient
         message.To.Add("Reciver.Email@gmail.com");
         
         // Add a message subject
         message.Subject = "Test Email Subject message";
         
         // Add a message body
         message.Body = "Test email Body message.";
         
         // Create a System.Net.Mail.MailAddress object and 
         // set the sender email address and display name.
         message.From = new MailAddress("Sender.Email@gmail.com", "John Smith");
         
         // Create a System.Net.Mail.SmtpClient object
         // and set the SMTP host and port number
         SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
         
         // If your server requires authentication add the below code
         // =========================================================
         // Enable Secure Socket Layer (SSL) for connection encryption
         smtp.EnableSsl = true;
         
         // Do not send the DefaultCredentials with requests
         smtp.UseDefaultCredentials = false;
         
         // Create a System.Net.NetworkCredential object and set
         // the username and password required by your SMTP account

1.try

 //        smtp.Credentials = new NetworkCredential("Sender.Email@gmail.com", "Password");
                 // Assets/SendEmail.cs(43,22): error CS0266: Cannot implicitly convert type `System.Net.NetworkCredential' to `System.Net.ICredentialsByHost'. An explicit conversion exists (are you missing a cast?)

2.try

 //        smtp.Credentials = (ICredentialsByHost) new NetworkCredential("Sender.Email@gmail.com", "Password");
                 // wow no error but when I run the code:
                 // InvalidOperationException: SSL authentication error: RemoteCertificateNotAvailable, RemoteCertificateChainErrors
                 // System.Net.Mail.SmtpClient.<callback>m__4 (System.Object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors)
                 // System.Net.Security.SslStream+<BeginAuthenticateAsClient>c__AnonStorey7.<>m__A (System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Int32[] certErrors)
                 // Mono.Security.Protocol.Tls.SslClientStream.OnRemoteCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] errors)
                 // Mono.Security.Protocol.Tls.SslStreamBase.RaiseRemoteCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] errors)
                 // Mono.Security.Protocol.Tls.SslClientStream.RaiseServerCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] certificateErrors)
                 // Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates)
                 // Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 ()
                 // Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process ()
                 // (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process ()
                 // Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg)
                 // Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult)
                 // Rethrow as IOException: The authentication or decryption has failed.
                 // Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult)
                 // Rethrow as SmtpException: Message could not be sent.
                 // System.Net.Mail.SmtpClient.Send (System.Net.Mail.MailMessage message)
                 // SendEmail.SendEmailF () (at Assets/SendEmail.cs:59)
                 // SendEmail.Start () (at Assets/SendEmail.cs:9)

3.try

 //        NetworkCredential myCred = new NetworkCredential("Sender.Email@gmail.com","Password");
 //        
 //        CredentialCache myCache = new CredentialCache();
 //        
 //        myCache.Add(new Uri("www.contoso.com"), "Basic", myCred);
 //        
 //        WebRequest wr = WebRequest.Create("www.contoso.com");
 //        smtp.Credentials = myCache;
                 // Assets/SendEmail.cs(69,33): error CS0246: The type or namespace name `Uri' could not be found. Are you missing a using directive or an assembly reference?
                 // Assets/SendEmail.cs(69,25): error CS1502: The best overloaded method match for `System.Net.CredentialCache.Add(System.Uri, string, System.Net.NetworkCredential)' has some invalid arguments
                 // Assets/SendEmail.cs(69,25): error CS1503: Argument `#1' cannot convert `object' expression to type `System.Uri'


the rest of the code

         // =========================================================
         
         // Send the message
         smtp.Send(message);
     }
 }

it's all in 1 BIG script but I only uncomment a line after 1,2,3 try and get an error that's commented

I made it like this to look a little bit more organized

and I'm using Unity 3D 4.1.2

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mrekuc · Mar 18, 2016 at 04:48 PM 0
Share

Is there a way to send from a gmail address to any address? Works perfect for sending to a gmail but what if you want to send to yahoo or some other @youraddress.com? @merry_christmas

avatar image madhu_unity425 · Feb 08, 2019 at 12:27 PM 0
Share

can anyone help me for the Webmails how to give the domain name

avatar image MFKJ · Dec 10, 2019 at 04:33 AM 0
Share

Here step by step guide : https://researchandprogram.blogspot.com/2019/12/how-to-send-email-form-unity3d-and-c.html

7 Replies

· Add your reply
  • Sort: 
avatar image
36
Best Answer

Answer by ByteSheep · Apr 08, 2013 at 11:29 AM

Adapted from http://stackoverflow.com/questions/4148019/authentication-or-decryption-has-failed-when-sending-mail-to-gmail-using-ssl

 using UnityEngine;
 using System.Collections;
 using System;
 using System.Net;
 using System.Net.Mail;
 using System.Net.Security;
 using System.Security.Cryptography.X509Certificates;
 
 public class mono_gmail : MonoBehaviour {
 
         void Main ()
         {
             MailMessage mail = new MailMessage();
 
             mail.From = new MailAddress("youraddress@gmail.com");
             mail.To.Add("youraddress@gmail.com");
             mail.Subject = "Test Mail";
             mail.Body = "This is for testing SMTP mail from GMAIL";
 
             SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
             smtpServer.Port = 587;
             smtpServer.Credentials = new System.Net.NetworkCredential("youraddress@gmail.com", "yourpassword") as ICredentialsByHost;
             smtpServer.EnableSsl = true;
             ServicePointManager.ServerCertificateValidationCallback = 
                 delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 
                     { return true; };
             smtpServer.Send(mail);
             Debug.Log("success");
         
         }
 }

This will send an email to a gmail account. Create a c# file in unity and name it 'mono_gmail'.
Don't forget to replace the email address with your own and of course add your password :)

Comment
Add comment · Show 20 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Richard 3 · Apr 25, 2013 at 11:25 AM 0
Share

Sweet Thanks, work perfectly!

avatar image sdgd · Apr 27, 2013 at 12:21 AM 0
Share

yeah I think not only the answer deserves lots of thumbs up as he did try figuering out about 3 days iirc but even the Q as there's only old and not accurate any longer threads and Questions for how to send Email :)

avatar image girishgowdayt · Jun 12, 2013 at 12:35 PM 0
Share

Thank you very much for the code.. it saved my 1 day..

avatar image Richard 3 · Oct 09, 2013 at 11:57 AM 2
Share

Got IT! I found out I had to set Api Compatibility Level to ".NET 2.0" ins$$anonymous$$d of ".NET 2.0 Subset" under player settings. Works great!!!

avatar image JuanMaldonado · Nov 08, 2016 at 07:47 PM 1
Share

For Standalone Builds, remember to change the API Compatibility Level in PlayerSettings/OtherSettings to .NET 2.0 not .NET 2.0 Subset.

Show more comments
avatar image
4

Answer by gooongalooo · Jul 04, 2015 at 05:56 PM

Better use

 client.SendAsync(message , "");

especially if you want to send some more stuff like attachments and so in ;) https://msdn.microsoft.com/de-de/library/x5x13z6h%28v=vs.110%29.aspx

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by jeryymanly · Jan 20, 2014 at 07:54 AM

A simple smtp email

             mail.From = new MailAddress("your_email_address@gmail.com");
             mail.To.Add("to_address");
             mail.Subject = "Test Mail";
             mail.Body = "This is for testing SMTP mail from GMAIL";

             SmtpServer.Port = 587;
             SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
             SmtpServer.EnableSsl = true;


source: http://csharp.net-informations.com/communications/csharp-smtp-mail.htm c# smtp

jery

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image isteffy · Feb 18, 2017 at 08:05 PM 0
Share

Great code. Great link. Thank you

avatar image
1

Answer by Falcon_DZ · Feb 25, 2016 at 07:58 AM

the above code by # merry_christmas works in standalone as well as in editor but it doesn't have any effect when build on webGL. can anyone tell what change has to be done to make it work? Thanks.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image fmathews34 · Jul 11, 2016 at 07:30 PM 0
Share

for some reason my project wont even load after i build it in webGL with this script included and the project crashes anytime i try to run the script even in the editor.

avatar image
1

Answer by Yuriy-Ivanov · Jun 18, 2017 at 06:32 PM

Unfortunately, Unity uses an outdated and buggy Mono 2.0 SmtpClient, which doesn't fully support STARTTLS protocol used my many modern SMTP servers. We've recently published a new asset UTMail - Email Composition and Sending Plugin, which doesn't have that issue and so works well with most SMTP servers (we've tested it with number of popular ones). It also allows not only directly sending emails with SMTP, but also composing emails using a system email client, with a content defined by your app. It works on multiple platforms and supports attachments and HTML / text messages.

Best regards,

Yuriy, Universal Tools team.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image tanoshimi · Jun 18, 2017 at 07:37 PM 0
Share

Please don't revive posts that were already answered over 4 years ago just to promote your new asset.

avatar image khemistry · Oct 10, 2017 at 04:26 AM 1
Share

This page still comes up on google really easily, and this response explained to me why the old answer wasn't working for me.

And the tool they are offering is exactly what I needed.

  • 1
  • 2
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

36 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

how to use Enum? C# I'm keep getting Unexpected symbol `enum' 2 Answers

Distribute terrain in zones 3 Answers

Add a byte[] as attachment in a mail 1 Answer

Sending email with Smtp client not working on Android 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges