Jak mogę wysyłać e-maile z mojej aplikacji na Androida?

Piszę aplikację na Androida. Jak mogę wysłać z niego wiadomość e-mail?

 469
Author: Amir Rachum, 2010-02-04

18 answers

Najlepszym (i najłatwiejszym) sposobem jest użycie Intent:

Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"[email protected]"});
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(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
W przeciwnym razie będziesz musiał napisać własnego klienta.
 902
Author: Jeremy Logan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-08 02:21:11

Użyj .setType("message/rfc822") lub wybranie wyświetli wszystkie (wiele) aplikacje obsługujące intencję send.

 185
Author: Jeff S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-22 20:12:37

Używam tego od dawna i wydaje się dobre, nie pojawiają się żadne aplikacje nie-E-mail. Po prostu inny sposób na wysłanie wiadomości e-mail:

Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject of email");
intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
intent.setData(Uri.parse("mailto:[email protected]")); // or just "mailto:" for blank
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(intent);
 77
Author: Randy Sugianto 'Yuku',
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-29 16:19:27

Używałem czegoś podobnego do aktualnie akceptowanej odpowiedzi, aby wysyłać e-maile z dołączonym plikiem binarnym dziennika błędów. GMail i K - 9 wysyłają go dobrze, a także przybywa dobrze na moim serwerze pocztowym. Jedynym problemem był mój klient poczty Thunderbird, który miał problemy z otwarciem / zapisaniem załączonego pliku dziennika. W rzeczywistości po prostu nie zapisał pliku bez narzekania.

Spojrzałem na jeden z tych kodów źródłowych poczty i zauważyłem, że plik dziennika załącznik miał (co zrozumiałe) typ mime message/rfc822. Oczywiście ten załącznik nie jest dołączonym e-mailem. Ale Thunderbird nie poradzi sobie z tym drobnym błędem z wdziękiem. Więc to było trochę kiepskie.

Po odrobinie badań i eksperymentów wymyśliłem następujące rozwiązanie:

    public Intent createEmailOnlyChooserIntent(Intent source,
        CharSequence chooserTitle) {
        Stack<Intent> intents = new Stack<Intent>();
        Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
                "[email protected]", null));
        List<ResolveInfo> activities = getPackageManager()
                .queryIntentActivities(i, 0);

        for(ResolveInfo ri : activities) {
            Intent target = new Intent(source);
            target.setPackage(ri.activityInfo.packageName);
            intents.add(target);
        }

        if(!intents.isEmpty()) {
            Intent chooserIntent = Intent.createChooser(intents.remove(0),
                    chooserTitle);
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                    intents.toArray(new Parcelable[intents.size()]));

            return chooserIntent;
        } else {
            return Intent.createChooser(source, chooserTitle);
        }
    }

Może być stosowany w następujący sposób:

        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("*/*");
        i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(crashLogFile));
        i.putExtra(Intent.EXTRA_EMAIL, new String[] {
            ANDROID_SUPPORT_EMAIL
        });
        i.putExtra(Intent.EXTRA_SUBJECT, "Crash report");
        i.putExtra(Intent.EXTRA_TEXT, "Some crash report details");

        startActivity(createEmailOnlyChooserIntent(i, "Send via email"));

Jak widać, metoda createEmailOnlyChooserIntent może być łatwo podawana z prawidłową intencją i prawidłowym typem mime.

It then przegląda listę dostępnych działań, które odpowiadają na intencję protokołu ACTION_SENDTO mailto (które są tylko aplikacjami e-mail) i konstruuje wybór na podstawie tej listy działań i oryginalnej intencji ACTION_SEND z prawidłowym typem mime.

Kolejną zaletą jest to, że Skype nie jest już wymieniony (co zdarza się reagować na typ MIME rfc822).

 49
Author: tiguchi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-09 16:07:55

To po prostu pozwól aplikacjom e-mail aby rozwiązać swój zamiar, musisz podać ACTION_SENDTO jako akcję i mailto jako dane.

private void sendEmail(){

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
    emailIntent.setData(Uri.parse("mailto:" + "[email protected]")); 
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My email's subject");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "My email's body");

    try {
        startActivity(Intent.createChooser(emailIntent, "Send email using..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(Activity.this, "No email clients installed.", Toast.LENGTH_SHORT).show();
    }

}
 32
Author: wildzic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-02 10:27:26

Strategia używania .setType("message/rfc822") lub ACTION_SEND wydaje się również pasować do aplikacji, które nie są klientami poczty e-mail, takich jak Android Beam i Bluetooth.

Używanie ACTION_SENDTO i mailto: URI wydaje się działać idealnie i jest zalecane w dokumentacji programisty. Jeśli jednak zrobisz to na oficjalnych emulatorach i nie ma skonfigurowanych kont e-mail (lub nie ma żadnych klientów pocztowych), otrzymasz następujący błąd:

Unsupported action

Ta akcja nie jest obecnie obsługiwana.

Jak pokazano poniżej:

Nieobsługiwana akcja: ta akcja nie jest obecnie obsługiwana.

Okazuje się, że emulatory rozwiązują intencję działania o nazwie com.android.fallback.Fallback, który wyświetla powyższy komunikat. najwyraźniej jest to projekt.

Jeśli chcesz, aby Twoja aplikacja omijała to, aby działała poprawnie na oficjalnych emulatorach, możesz sprawdzić to przed próbą wysłania e-maila:

private void sendEmail() {
    Intent intent = new Intent(Intent.ACTION_SENDTO)
        .setData(new Uri.Builder().scheme("mailto").build())
        .putExtra(Intent.EXTRA_EMAIL, new String[]{ "John Smith <[email protected]>" })
        .putExtra(Intent.EXTRA_SUBJECT, "Email subject")
        .putExtra(Intent.EXTRA_TEXT, "Email body")
    ;

    ComponentName emailApp = intent.resolveActivity(getPackageManager());
    ComponentName unsupportedAction = ComponentName.unflattenFromString("com.android.fallback/.Fallback");
    if (emailApp != null && !emailApp.equals(unsupportedAction))
        try {
            // Needed to customise the chooser dialog title since it might default to "Share with"
            // Note that the chooser will still be skipped if only one app is matched
            Intent chooser = Intent.createChooser(intent, "Send email with");
            startActivity(chooser);
            return;
        }
        catch (ActivityNotFoundException ignored) {
        }

    Toast
        .makeText(this, "Couldn't find an email app and account", Toast.LENGTH_LONG)
        .show();
}

Znajdź więcej informacji w deweloper dokumentacja .

 18
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-25 13:52:05

Rozwiązałem ten problem za pomocą prostych linii kodu, jak wyjaśnia dokumentacja Androida.

(https://developer.android.com/guide/components/intents-common.html#Email )

Najważniejsza jest flaga: jest ACTION_SENDTO, i nie ACTION_SEND

Druga ważna linia to

intent.setData(Uri.parse("mailto:")); ***// only email apps should handle this***

Przy okazji, jeśli wyślesz pusty Extra, if() na końcu nie będzie działać i aplikacja nie uruchomi klienta poczty e-mail.

Według Androida dokumentacja. Jeśli chcesz mieć pewność, że Twój zamiar jest obsługiwany tylko przez aplikację e-mail (a nie inne wiadomości tekstowe lub aplikacje społecznościowe), użyjACTION_SENDTO działania i obejmują "mailto:" schemat danych. Na przykład:

public void composeEmail(String[] addresses, String subject) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}
 15
Author: Pedro Varela,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-26 14:13:06

Wysyłanie wiadomości e-mail może odbywać się z intencjami, które nie wymagają konfiguracji. Ale wtedy będzie to wymagało interakcji użytkownika, a układ będzie nieco ograniczony.

Budowanie i wysyłanie bardziej złożonych wiadomości e-mail bez interakcji z użytkownikiem wiąże się z budowaniem własnego klienta. Pierwszą rzeczą jest to, że Sun Java API dla poczty e-mail są niedostępne. Udało mi się wykorzystać bibliotekę Apache Mime4j do budowania poczty e-mail. Wszystko na podstawie dokumentów na nilvec .

 12
Author: Rene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-27 13:17:29

Simple try this one

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    buttonSend = (Button) findViewById(R.id.buttonSend);
    textTo = (EditText) findViewById(R.id.editTextTo);
    textSubject = (EditText) findViewById(R.id.editTextSubject);
    textMessage = (EditText) findViewById(R.id.editTextMessage);

    buttonSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            String to = textTo.getText().toString();
            String subject = textSubject.getText().toString();
            String message = textMessage.getText().toString();

            Intent email = new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
            // email.putExtra(Intent.EXTRA_CC, new String[]{ to});
            // email.putExtra(Intent.EXTRA_BCC, new String[]{to});
            email.putExtra(Intent.EXTRA_SUBJECT, subject);
            email.putExtra(Intent.EXTRA_TEXT, message);

            // need this to prompts email client only
            email.setType("message/rfc822");

            startActivity(Intent.createChooser(email, "Choose an Email client :"));

        }
    });
}
 3
Author: NagarjunaReddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-04 12:59:03

Używam poniższego kodu w moich aplikacjach. Pokazuje to dokładnie aplikacje klienta poczty e - mail, takie jak Gmail.

    Intent contactIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.email_to), null));
    contactIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject));
    startActivity(Intent.createChooser(contactIntent, getString(R.string.email_chooser)));
 3
Author: lomza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-20 17:48:24

Oto przykładowy kod roboczy, który otwiera aplikację pocztową w urządzeniu z Androidem i automatycznie wypełnia adresami i temat w składającej się wiadomości.

protected void sendEmail() {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:[email protected]"));
    intent.putExtra(Intent.EXTRA_SUBJECT, "Feedback");
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}
 3
Author: Sridhar Nalam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-16 19:16:01

Innym rozwiązaniem może być

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.setType("plain/text");
emailIntent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Yo");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi");
startActivity(emailIntent);

Zakładając, że większość urządzeń z Androidem ma już zainstalowaną aplikację GMail.

 2
Author: silentsudo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-28 09:55:04

Użyj tego do wysyłania wiadomości e-mail...

boolean success = EmailIntentBuilder.from(activity)
    .to("[email protected]")
    .cc("[email protected]")
    .subject("Error report")
    .body(buildErrorReport())
    .start();

Użyj build gradle :

compile 'de.cketti.mailto:email-intent-builder:1.0.0'
 2
Author: Manish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-24 11:32:10

Ta funkcja najpierw direct intent gmail do wysyłania wiadomości e-mail, jeśli gmail nie zostanie znaleziony, a następnie Promuj wybór intencji. Używałem tej funkcji w wielu komercyjnych aplikacjach i działa dobrze. Mam nadzieję, że ci pomoże:

public static void sentEmail(Context mContext, String[] addresses, String subject, String body) {

    try {
        Intent sendIntentGmail = new Intent(Intent.ACTION_VIEW);
        sendIntentGmail.setType("plain/text");
        sendIntentGmail.setData(Uri.parse(TextUtils.join(",", addresses)));
        sendIntentGmail.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
        sendIntentGmail.putExtra(Intent.EXTRA_EMAIL, addresses);
        if (subject != null) sendIntentGmail.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (body != null) sendIntentGmail.putExtra(Intent.EXTRA_TEXT, body);
        mContext.startActivity(sendIntentGmail);
    } catch (Exception e) {
        //When Gmail App is not installed or disable
        Intent sendIntentIfGmailFail = new Intent(Intent.ACTION_SEND);
        sendIntentIfGmailFail.setType("*/*");
        sendIntentIfGmailFail.putExtra(Intent.EXTRA_EMAIL, addresses);
        if (subject != null) sendIntentIfGmailFail.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (body != null) sendIntentIfGmailFail.putExtra(Intent.EXTRA_TEXT, body);
        if (sendIntentIfGmailFail.resolveActivity(mContext.getPackageManager()) != null) {
            mContext.startActivity(sendIntentIfGmailFail);
        }
    }
}
 2
Author: Shohan Ahmed Sijan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-22 10:05:39

To pokaże tylko klientów poczty e-mail (jak również PayPal z jakiegoś nieznanego powodu)

 public void composeEmail() {

    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:"));
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    intent.putExtra(Intent.EXTRA_TEXT, "Body");
    try {
        startActivity(Intent.createChooser(intent, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }
}
 2
Author: Avi Parshan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-01 09:08:38

Tak to zrobiłem. Ładnie i prosto.

String emailUrl = "mailto:[email protected]?subject=Subject Text&body=Body Text";
        Intent request = new Intent(Intent.ACTION_VIEW);
        request.setData(Uri.parse(emailUrl));
        startActivity(request);
 1
Author: Dog Lover,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-23 14:24:22

Ta metoda działa dla mnie. Otwiera aplikację Gmail (jeśli jest zainstalowana) i ustawia mailto.

public void openGmail(Activity activity) {
    Intent emailIntent = new Intent(Intent.ACTION_VIEW);
    emailIntent.setType("text/plain");
    emailIntent.setType("message/rfc822");
    emailIntent.setData(Uri.parse("mailto:"+activity.getString(R.string.mail_to)));
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.app_name) + " - info ");
    final PackageManager pm = activity.getPackageManager();
    final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
    ResolveInfo best = null;
    for (final ResolveInfo info : matches)
        if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
            best = info;
    if (best != null)
        emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
    activity.startActivity(emailIntent);
}
 0
Author: psycho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-26 20:53:43

Użyłem tego kodu, aby wysłać pocztę, uruchamiając domyślną sekcję kompozycji aplikacji pocztowej bezpośrednio.

    Intent i = new Intent(Intent.ACTION_SENDTO);
    i.setType("message/rfc822"); 
    i.setData(Uri.parse("mailto:"));
    i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"[email protected]"});
    i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    i.putExtra(Intent.EXTRA_TEXT   , "body of email");
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }
 0
Author: Faris Muhammed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-29 05:31:26