Tuesday, August 21, 2018

Android Launching Email Client (app support) using Intents

If you want to launch an email client (composing a new email), you can use the power of Intents to achieve that. The email client can be launched by pre filling the certain details like to addresssubjectbody and optional attachment.
Typically this will be used in the app, when you want to provide email support. The function below also attaches device information like OS versiondevice manufacturer and other useful device information to provide further support.
public static void contactHelpAndSupport(Context context, String[] to, String subject) {
    String body = "";
    try {
        body = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        body = "How can we help?\n\n\n\n\n\n\nPlease do not delete below contents\nDevice OS: Android(" +
                Build.VERSION.RELEASE + ")\n App v" + body + "\n Device: " + Build.BRAND +
                ", " + Build.MODEL;
    } catch (PackageManager.NameNotFoundException e) {
    }
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL, to);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, body);
    context.startActivity(Intent.createChooser(intent, "Send email:"));
}
Here is the full code snippet to call the email client.


MainActivity.java
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // pass array of to email ids
        contactHelpAndSupport(this, new String[]{"contact@revihost.com", "admin@revihost.com"}, "App help & support");
    }
 
    public static void contactHelpAndSupport(Context context, String[] to, String subject) {
        String body = "";
        try {
            body = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
            body = "How can we help?\n\n\n\n\n\n\nPlease do not delete below contents\nDevice OS: Android(" +
                    Build.VERSION.RELEASE + ")\n App v" + body + "\n Device: " + Build.BRAND +
                    ", " + Build.MODEL;
        } catch (PackageManager.NameNotFoundException e) {
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("message/rfc822");
        intent.putExtra(Intent.EXTRA_EMAIL, to);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        intent.putExtra(Intent.EXTRA_TEXT, body);
        context.startActivity(Intent.createChooser(intent, "Send email:"));
    }
}

No comments:

Post a Comment

AJAX - Quick Guide