Android activity send email

Отправка E-Mail средствами Android

Привет хабр и привет всем!

В данной статье я покажу как реализуется отправка писем средствами самого Android, а также ещё один более интересный способ, но уже с применением внешней библиотеки, которая позволяет нам отсылать письма более приемлимыми для программиста способами.

Часть 1. Mail, просто Mail

  1. public class SimpleEMail extends Activity <
  2. Button send;
  3. EditText address, subject, emailtext;
  4. @Override
  5. public void onCreate(Bundle savedInstanceState) <
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.simple_email);
  8. // Наши поля и кнопка
  9. send = (Button) findViewById(R.id.emailsendbutton);
  10. address = (EditText) findViewById(R.id.emailaddress);
  11. subject = (EditText) findViewById(R.id.emailsubject);
  12. emailtext = (EditText) findViewById(R.id.emailtext);
  13. send.setOnClickListener( new OnClickListener() <
  14. @Override
  15. public void onClick(View v) <
  16. final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
  17. emailIntent.setType( «plain/text» );
  18. // Кому
  19. emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
  20. new String [] < address.getText().toString() >);
  21. // Зачем
  22. emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
  23. subject.getText().toString());
  24. // О чём
  25. emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
  26. emailtext.getText().toString());
  27. // С чем
  28. emailIntent.putExtra(
  29. android.content.Intent.EXTRA_STREAM,
  30. Uri .parse( «file://»
  31. + Environment.getExternalStorageDirectory()
  32. + «/Клипы/SOTY_ATHD.mp4» ));
  33. emailIntent.setType( «text/video» );
  34. // Поехали!
  35. SimpleEMail. this .startActivity(Intent.createChooser(emailIntent,
  36. «Отправка письма. » ));
  37. >
  38. >);
  39. >
  40. >

* This source code was highlighted with Source Code Highlighter .

Вот, код до безобразия прост. Правда можно еще проще: если нам лень создавать дополнительное Activity для ввода наших полей, то можно было бы просто запустить наш Intent.

Плюсы: Простая реализация, достаточно удобно для обратной связи.
Минусы: У пользователя должна быть настроенная программа приёма-передачи почтовых сообщений, без неё обрабатывать данный Intent будет некому.

Часть 2. Mail, анонимус Mail

Данный метод я использовал в своём проекте, обозначим для начала плюсы:

  • Не требует от пользователя настроенного клиента
  • Может быть полностью анонимным
  • Можно передавать все (в пределах разумного, конечно)

Для работы необходимы дополнительные библиотеки javamail-android.
Качаем их, и встраиваем в проект: Контекстное меню проекта > «Build Path» > «Add External Archives. » > «Наши файлы additional, mail, activation»

Для настройки нам также понадобится почтовый ящик зарегистрированный на gmail.com (или любом другом yandex, mail и.т.п.) настройки вы можете посмотреть здесь. В данном случае он будет выступать в виде шлюза через которые будут проходить наши письма.

Начинаем настраивать:
MailSenderClass.java
В данном классе записаны настройки того сервера, через который будет передаваться ваше сообщение. Здесь у нас есть несколько методов:

  • public MailSenderClass(String user, String password) — Конструктор. В качестве аргументов передаются логин и пароль от нашего промежуточного ящика на gmail.com. Здесь же прописываются параметры smtp-подключения к серверу.
  • protected PasswordAuthentication getPasswordAuthentication() — Аутентификация для сервера.
  • public synchronized void sendMail(String subject, String body, String sender, String recipients, String filename) — Основной метод, в который передаются наши данные для отправки.
Читайте также:  Как сделать загрузочный диск android

Рассмотрим код последнего метода чуть ближе:

  1. public synchronized void sendMail( String subject, String body, String sender, String recipients, String filename) throws Exception <
  2. try <
  3. MimeMessage message = new MimeMessage(session);
  4. // Кто
  5. message.setSender( new InternetAddress(sender));
  6. // О чем
  7. message.setSubject(subject);
  8. // Кому
  9. if (recipients.indexOf( ‘,’ ) > 0)
  10. message.setRecipients(Message.RecipientType.TO,
  11. InternetAddress.parse(recipients));
  12. else
  13. message.setRecipient(Message.RecipientType.TO,
  14. new InternetAddress(recipients));
  15. // Хочет сказать
  16. BodyPart messageBodyPart = new MimeBodyPart();
  17. messageBodyPart.setText(body);
  18. _multipart.addBodyPart(messageBodyPart);
  19. // И что показать
  20. if (!filename.equalsIgnoreCase( «» )) <
  21. BodyPart attachBodyPart = new MimeBodyPart();
  22. DataSource source = new FileDataSource(filename);
  23. attachBodyPart.setDataHandler( new DataHandler(source));
  24. attachBodyPart.setFileName(filename);
  25. _multipart.addBodyPart(attachBodyPart);
  26. >
  27. message.setContent(_multipart);
  28. Transport.send(message);
  29. > catch (Exception e) <
  30. Log.e( «sendMail» , «Ошибка отправки функцией sendMail! » );
  31. >
  32. >

* This source code was highlighted with Source Code Highlighter .

Метод также прост. Используя объект класса MimeMessage составляем наше письмо и для отправки передаём методу send, класса Transport.

JSSEProvider.java
Провайдер протокола безопасности для нашей почты. Линк.

VideoSelect.java
Код был взят из ApiDemos, которые поставляются в комплекте с Android SDK, и был чуть подправлен для выполнения с помощью метода startActivityForResult.
После выполнения возвращается строка, содержащая путь к файлу на карте памяти. Код можно будет посмотреть в проекте, он в конце статьи.

ExtendedMail.java
Основной метод отправления сообщения выполняется в функции sitv_sender_mail_async, представляющей класс AsyncTask:

  1. private class sender_mail_async extends AsyncTask String , Boolean><
  2. ProgressDialog WaitingDialog;
  3. @Override
  4. protected void onPreExecute() <
  5. // Выводим пользователю процесс загрузки
  6. WaitingDialog = ProgressDialog.show(ExtendedMail. this , «Отправка данных» , «Отправляем сообщение. » , true );
  7. >
  8. @Override
  9. protected void onPostExecute(Boolean result) <
  10. // Прячем процесс загрузки
  11. WaitingDialog.dismiss();
  12. Toast.makeText(mainContext, «Отправка завершена. » , Toast.LENGTH_LONG).show();
  13. ((Activity)mainContext).finish();
  14. >
  15. @Override
  16. protected Boolean doInBackground(Object. params ) <
  17. try <
  18. // Получаем данные с наших полей
  19. title = ((EditText)findViewById(R.id.screen_sendnews_et_title)).getText().toString();
  20. text = ((EditText)findViewById(R.id.screen_sendnews_et_text)).getText().toString();
  21. from = «from_post_msg@gmail.com» ;
  22. where = «where_post_msg@yandex.ru» ;
  23. // Вызываем конструктор и передаём в него наши логин и пароль от ящика на gmail.com
  24. MailSenderClass sender = new MailSenderClass( «mypostmail@gmail.com» , «password» );
  25. // И вызываем наш метод отправки
  26. sender.sendMail(title, text, from , where , attach);
  27. > catch (Exception e) <
  28. Toast.makeText(mainContext, «Ошибка отправки сообщения!» , Toast.LENGTH_SHORT).show();
  29. >
  30. return false ;
  31. >
  32. >

* This source code was highlighted with Source Code Highlighter .

  1. public void onClick(View v) <
  2. sender_mail_async async_sending = new sender_mail_async();
  3. async_sending.execute();
  4. >

* This source code was highlighted with Source Code Highlighter .

Таким образом создав небольшой класс-поток, можно спокойно слать необходимую информацию от клиента к себе на ящик.

Источник

Android Send Email with Examples

In android, we can easily send an email from our android application using existing email clients such as GMAIL, Outlook, etc. instead of building an email client from scratch.

Generally, the Intent object in android with proper action (ACTION_SEND) and data will help us to launch the available email clients to send an email in our application.

In android, Intent is a messaging object which is used to request an action from another app component such as activities, services, broadcast receivers, and content providers. To know more about an Intent object in android check this Android Intents with Examples.

Читайте также:  Android получать текущее время

To send an email using the Intent object in android application, we need to write the code as shown below.

If you observe above code we used multiple components to send email, those are

it — Our local implicit intent

ACTION_SEND — It’s an activity action that specifies that we are sending some data.

putExtra — we use this putExtra() method to add extra information to our Intent. Here we can add the following things.

  • EXTRA_EMAIL — It’s an array of email addresses
  • EXTRA_SUBJECT — The subject of the email that we want to send
  • EXTRA_TEXT — The body of the email

The android Intent object is having different options such as EXTRA_CC, EXTRA_BCC, EXTRA_HTML_TEXT, EXTRA_STREAM, etc. to add different options for an email client.

setType — We use this property to set the MIME type of data that we want to send. Here we used “message/rfc822” and other MIME types are “text/plain” and “image/jpg”.

Now we will see how to send an email in android application using an Intent object with examples.

Android Send Email Example

Following is the example of sending an email with existing email clients using Intent in the android application.

Create a new android application using android studio and give names as SendMailExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :layout_width= «match_parent»
android :layout_height= «match_parent»
android :paddingLeft= «20dp»
android :paddingRight= «20dp»
android :orientation= «vertical» >
EditText
android :id= «@+id/txtTo»
android :layout_width= «match_parent»
android :layout_height= «wrap_content»
android :hint= «To»/>
EditText
android :id= «@+id/txtSub»
android :layout_width= «match_parent»
android :layout_height= «wrap_content»
android :hint= «Subject»/>
EditText
android :id= «@+id/txtMsg»
android :layout_width= «match_parent»
android :layout_height= «0dp»
android :layout_weight= «1»
android :gravity= «top»
android :hint= «Message»/>
Button
android :layout_width= «100dp»
android :layout_height= «wrap_content»
android :layout_gravity= «right»
android :text= «Send»
android :id= «@+id/btnSend»/>
LinearLayout >

Now open our main activity file MainActivity.java from \src\main\java\com.tutlane.sendmailexample path and write the code like as shown below

MainActivity.java

package com.tutlane.sendmailexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity <

private EditText eTo ;
private EditText eSubject ;
private EditText eMsg ;
private Button btn ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
eTo = (EditText)findViewById(R.id. txtTo );
eSubject = (EditText)findViewById(R.id. txtSub );
eMsg = (EditText)findViewById(R.id. txtMsg );
btn = (Button)findViewById(R.id. btnSend );
btn .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
Intent it = new Intent(Intent. ACTION_SEND );
it.putExtra(Intent. EXTRA_EMAIL , new String[]< eTo .getText().toString()>);
it.putExtra(Intent. EXTRA_SUBJECT , eSubject .getText().toString());
it.putExtra(Intent. EXTRA_TEXT , eMsg .getText());
it.setType( «message/rfc822» );
startActivity(Intent.createChooser(it, «Choose Mail App» ));
>
>);
>
>

Читайте также:  Что такое мобильный оператор для андроид

If you observe above code we used multiple components to send email, those are

it — Our local implicit intent

ACTION_SEND — It’s an activity action that specifies that we are sending some data.

putExtra — we use this putExtra() method to add extra information to our Intent. Here we can add the following things.

  • EXTRA_EMAIL — It’s an array of email addresses
  • EXTRA_SUBJECT — The subject of the email that we want to send
  • EXTRA_TEXT — The body of the email

setType — We use this property to set the MIME type of data that we want to send. Here we used “message/rfc822” and other MIME types are “text/plain” and “image/jpg”.

We need to add MIME type in our android manifest file for that open android manifest file (AndroidManifest.xml) and write the code like as shown below

AndroidManifest.xml

xml version= «1.0» encoding= «utf-8» ?>
manifest xmlns: android = «http://schemas.android.com/apk/res/android» package= «com.tutlane.sendmailexample» >
application
android :allowBackup= «true»
android :icon= «@mipmap/ic_launcher»
android :label= «@string/app_name»
android :roundIcon= «@mipmap/ic_launcher_round»
android :supportsRtl= «true»
android :theme= «@style/AppTheme» >
activity android :name= «.MainActivity» >
intent-filter >
action android :name= «android.intent.action.MAIN»/>
category android :name= «android.intent.category.LAUNCHER»/>
action android :name= «android.intent.action.SEND»/>
category android :name= «android.intent.category.DEFAULT»/>
data android :mimeType= «message/rfc822»/>
intent-filter >
activity >
application >
manifest >

If you observe above AndroidManifest.xml file we added following extra fields of Intent filters.

action — we use this property to define that the activity can perform SEND action.

category — we included the DEFAULT category for this activity to be able to receive implicit intents.

data — the type of data the activity can send.

Output of Android Send Email Example

When we run above program in the android studio we will get the result like as shown below.

Once we enter all the details and click on Send button, it will display a dialog with the apps which are capable of sending an email. By selecting the required email client we can send an email without building our own email client like as shown below.

This is how we can send emails using intents in android applications based on our requirements.

Источник

Оцените статью