How to make an email address clickable?

This is a very reasonable request and the Linkify class will turn every email address into an appropriate link for you. Simply add the autoLink attribute to your XML:

<TextView
    ...
    android:autoLink="email" />

You can make your text clickable by using setOnClickListener on the text

textView.setOnClickListener(new View.OnClickListener());

You can open the email client by creating a new Intent with the ACTION_SEND. Settype, the email address and subject like this:

Intent emailintent = new Intent(android.content.Intent.ACTION_SEND);
emailintent.setType("plain/text");
emailintent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[] {"[email protected]" });
emailintent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
emailintent.putExtra(android.content.Intent.EXTRA_TEXT,"");
startActivity(Intent.createChooser(emailintent, "Send mail..."));

You need to fire an intent in your onClickListener:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain"); // send email as plain text
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" });
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));

Please be aware of a little bug from API 24 onwards which makes the accepted solution not work if the local part of the email address has exactly 2 characters like "[email protected]".

See the issue: https://issuetracker.google.com/issues/64435698

Allegedly fixed already, but apparently not rolled out yet. (Don't you love it that they know about the issue and don't even bother to update the documentation accordingly? https://developer.android.com/reference/android/widget/TextView.html#attr_android:autoLink)

So unless you're sure that you're not dealing with such 2-letter email addresses, you should rather use the accepted approach from here for the time being:

TextView to send email when clicked

Take care to remove the autolink attribute from the TextView then.

Tags:

Android