Mhche
Mhche

Reputation: 143

Send email to multiple recipients from array

I store in my Database emails, i query my db to return a list with all emails.Then in my activity i get them all to a String array (String[]) and then try to get them at a single string so to put them as recipients but at the end only takes my last email from the string.

Here is my code:

                DatabaseHandler db = new DatabaseHandler(
                    getApplicationContext());
            ArrayList<String> array_from_db = db.Get_Students_Email();
            String emails = "";

            for (int i = 0; i < array_from_db.size(); i++) {

                 emails = emails + array_from_db.get(i).toString() + ";";

            }
            db.close();

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

I have tried also

in.putExtra(Intent.EXTRA_EMAIL, emails);

and uri parse but still nothing happen.

Upvotes: 0

Views: 2326

Answers (2)

rakrakrakrak
rakrakrakrak

Reputation: 69

Or you can simply do:

Intent i = new Intent(Intent.ACTION_SENDTO);
i.setType("message/rfc822");
String uriText = "mailto:" + email_concactenated_with_commas +
                 "?subject=" + your_subject + 
                 "&body=" + your_body
Uri uri = Uri.parse(uriText);
intent.setData(uri);

It's fine to just separate the email addresses with commas and no spaces in the String of emails. The email application will pick up on the multiple addresses exactly the same way you would enter multiple email addresses from your computer by separating them with commas.

Upvotes: 1

Submersed
Submersed

Reputation: 8870

in.putExtra(Intent.EXTRA_EMAIL, new String[] { emails }); 

Requires a String array of emails. Right now, you're just concatenating all of the emails into one long String, then constructing a single length string array from that, instead actually building an array of emails.

Make the following change:

 String[] emails = new String[array_from_db.size()];

            for (int i = 0; i < array_from_db.size(); i++) {

                 emails[i] = array_from_db.get(i);

            }

Then just use:

in.putExtra(Intent.EXTRA_EMAIL, emails ); 

Edit:

Or, an even more concise way to handle it would be just using the ArrayList method:

   String[] emails = new String[array_from_db.size()];
   array_from_db.toArray(emails);

Upvotes: 2

Related Questions