Sending email on android device

Hi,

I try to send email using c#.net.mail library. Emails can be sent to my email address seamlessly when i working with unityeditor but cannot be sent if i push the project to the android device. I’m using free version of unity3d. What the problem may be related to?

My code is below;

using System;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public class EMail {

    public static void Send(string message) {

        MailMessage mail = new MailMessage();
        mail.From = new MailAddress("mymailaddress@gmail.com");
        mail.To.Add("mymailaddress@gmail.com");
        mail.Subject = "Subject";
        mail.Body = message;

        SmtpClient smtp = new SmtpClient("smtp.gmail.com");
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential("mymailaddress@gmail.com", "mypassword") as ICredentialsByHost;
        smtp.EnableSsl = true;

        ServicePointManager.ServerCertificateValidationCallback =
                delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
                    return true;
                };
        smtp.Send(mail);
    }
}

I’m not sure that .Net can send emails on mobile cells.
Here is a toolkit that declare e-mail sending on android devises - Unity Asset Store - The Best Assets for Game Making

thansk for reply :slight_smile:

I checked “.NET2.0” instead of “.NET2.0 Subset” in the player settings and problem is solved.

2 Likes

It’s great!

Above code i have copy pasted, even after changing to “.NET2.0” i’m not able to send mails through android device, it works fine in unity Editor. What else changes i have to do in player settings?

I have tried the same above code and changed the assembly to .NET 2.0 from .NET 2.0 Subset, but still i am unable to send from android where as i can send using unity editor without problems. Can anyone help what am i missing?

I have also had the same problem, changed the assembly to .NET 2.0 and was unsuccessful at first. But, when i changed to development build, then it worked suddenly. I am not sure why this is working in development build but not the final release, but i suppose that it is something about internal android security. It is needed to be investigated, but if you will not publish your application but will use on a limited hardware then this may be a work around.

1 Like

Even though this is an old post, I am going to post my solution for anybody else having this problem that needs a fix for a full release.

I got this to work without development build in .NET 2.0. It was such a simple fix, yet so complicated hah.

so the problem was in actually sending the mail message in smtp.Send(mail);
but this was not why it didn’t send.

I believe, but i’m not 100% sure, it didn’t send because

SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Port = 587;

will setup the smtp.gmail.com host in the editor, but when built for android, somehow it is skipping over that bit of information and doesn’t know which host to connect too.

With that said, the only thing I needed to change to make this work for Android full release was change that last bit of code to:

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;

It works for me if anybody else wants to try this.
along with the .NET 2.0 under player settings, I selected to option to require internet access

Also I added this bit of code to make sure it was sending the email over the network.

smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

Please correct me if I am wrong anywhere.

Hello Mike, I try to do what you said, but it won’t work, any tips ? best

here is my code:

void sendEmail () {
        MailMessage mail = new MailMessage();
       
        mail.From = new MailAddress("xxxxxx@gmail.com");
        mail.To.Add("xxxxxxx@gmail.com");
        mail.Subject = System.DateTime.Now.ToString("MM/dd/yyyy");
        mail.Body = SaveClientInformation.getClientsInString ();
       
        SmtpClient smtpServer = new SmtpClient();
        smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpServer.Host = "smtp.gmail.com";
        smtpServer.Port = 587;
        smtpServer.Credentials = new System.Net.NetworkCredential("icadunas@gmail.com", "xxxxxxx") as ICredentialsByHost;
        smtpServer.EnableSsl = true;
        ServicePointManager.ServerCertificateValidationCallback =
            delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        { return true; };
        smtpServer.Send(mail);
        SaveClientInformation.clearSavedClients();
        Debug.Log("success");
    }

I did get this to work on my android build using the code above and the .net ticked. Now i want to send an attachment from the android build. But i cannot access the atatchment file. I think you can use WWW but i am unsure how to do this.

in unity i can use

System.Net.Mail.Attachmentattachment;
attachment=new System.Net.Mail.Attachment(Application.dataPath+“/StreamingAssets/test.rtf”);
mail.Attachments.Add(attachment);

it works but i need to alter it to work in android.

Can Anybody advise?

Hey @mark-pollard

I use the following method to attach images to an email which is sent from an Android device, hope it helps you. :slight_smile:

private void AddAttachments (List<string> attachmentsPath) {
        // Clear Attachments List
        _email.Attachments.Clear ();
        // "Attachments" is a AttachmentCollection that cannot be SET
        for (int index = 0; index < attachmentsPath.Count; index++) {
            try {
                System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment (attachmentsPath[index]);
                _email.Attachments.Add (attachment);
            } catch (Exception ex) {
                Debug.Log("Exception Error: " + ex);
                //break;
            }
        }
    }

The contents of “attachmentsPath” is the strings obtained after using:

string _attachmentPath = Application.persistentDataPath + "/YourPathToYourAttachment/";

Note the previous line of code returns the path to one attachment, not all of them. If you want to get all of them you should be reading the folder where your attachments are and adding them to a List.

Dear patico,
I’ve changed “.NET2.0” instead of “.NET2.0 Subset” in the player settings,
Still the problem was continues.
Can u tell me What i’ve to change

2615596–183508–mono_gmail.cs (1.41 KB)

I have the same problem, send email only work on android if the game is on development build… someone have a solution?

Here are some things that I ran into with this. You are probably missing the Android Manifest File for permissions because developer’s version doesn’t need it while releasing does.

1) .Net 2.0
2) stripping to disabled.
3) change the Android manifest (xml document) to include permissions for internet and WIFI (if you do not change the manifest it will not have the ability to send because you didnt give the phone the ability too)

with that being said. With those setting I am able to send an email on many android systems, such as Google Pixel, Amazon Kindle, LGE 4G, and Samsung SM, but certain android devices fail to deliver a message everytime on devices like the Galaxy 6. If anyone has anything else let me know but those are things I found out that helped.

I know it’s a bit late but I thought I would still thank OrangeCanine for their suggestion. In case anybody else needs it my code is below in C#. The problem for me was the striping level. .Net was set to 2.0, not subset, and I did not need to change the manifest. This did work on a Galaxy s4, s6, and Note 5.

    void SendMail(string aFrom, string aTo, string aSubject, string aBody, string aPassword)
    {
        if (!aTo.Contains("@") && !aTo.ToLower().Contains(".com"))
            return;

        MailMessage mail = new MailMessage();

        mail.From = new MailAddress(aFrom);
        mail.To.Add(aTo);
        mail.Subject = aSubject;
        mail.Body = aBody;

        SmtpClient smtpServer = new SmtpClient();
        smtpServer.Host = "smtp.gmail.com";
        smtpServer.Port = 587;
        smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpServer.Credentials = new System.Net.NetworkCredential(aFrom, aPassword) as ICredentialsByHost;
        smtpServer.EnableSsl = true;
        ServicePointManager.ServerCertificateValidationCallback =
            delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            { return true; };
        smtpServer.Send(mail);
    }

Even later comment on this but thought I’d share what we found out as well. Only change we needed to do was to change Player settings - Android - Internet Access → Require. This adds the following line to AndroidManifest.xml:

After this emails are coming to gmail account. Unity editor 5.5.0f3 with Samsung Galaxy Tab 4 used in testing.

a great thank you

Thanks!!!
I can’t believe that I spent hours to tickle this silly problem!!

2 Likes

it worked for me too, thanks