joey joey -4 years ago 91
Android Question

How do I send Email using an email client?

I am trying to-


  1. get my own primary email

  2. set the primary email as recipient's address so I can send an email
    to Myself



This is how I get my primary email-

Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(getBaseContext())
.getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
Toast.makeText(this, possibleEmail, Toast.LENGTH_LONG)
.show();
}
}


and this is how I send email-

Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL,
new String[] { "recipient@example.com" });
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT, "body of email");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Main.this,
"There are no email clients installed.",
Toast.LENGTH_SHORT).show();
}


How do I give
EXTRA_EMAIL
my primary email?

Answer Source

Solution:

    String possibleEmail = null;
    Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
    Account[] accounts = AccountManager.get(getBaseContext())
            .getAccounts();
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            possibleEmail = account.name;
            Toast.makeText(this, possibleEmail, Toast.LENGTH_LONG)
                    .show();
        }
    }

    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_EMAIL, new String[]{possibleEmail});
    i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
    i.putExtra(Intent.EXTRA_TEXT, "body of email");
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(Main.this,
                "There are no email clients installed.",
                Toast.LENGTH_SHORT).show();
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download