Отправка E-Mail средствами Android
Привет хабр и привет всем!
В данной статье я покажу как реализуется отправка писем средствами самого Android, а также ещё один более интересный способ, но уже с применением внешней библиотеки, которая позволяет нам отсылать письма более приемлимыми для программиста способами.
Часть 1. Mail, просто Mail
- public class SimpleEMail extends Activity <
- Button send;
- EditText address, subject, emailtext;
- @Override
- public void onCreate(Bundle savedInstanceState) <
- super.onCreate(savedInstanceState);
- setContentView(R.layout.simple_email);
- // Наши поля и кнопка
- send = (Button) findViewById(R.id.emailsendbutton);
- address = (EditText) findViewById(R.id.emailaddress);
- subject = (EditText) findViewById(R.id.emailsubject);
- emailtext = (EditText) findViewById(R.id.emailtext);
- send.setOnClickListener( new OnClickListener() <
- @Override
- public void onClick(View v) <
- final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
- emailIntent.setType( «plain/text» );
- // Кому
- emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
- new String [] < address.getText().toString() >);
- // Зачем
- emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
- subject.getText().toString());
- // О чём
- emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
- emailtext.getText().toString());
- // С чем
- emailIntent.putExtra(
- android.content.Intent.EXTRA_STREAM,
- Uri .parse( «file://»
- + Environment.getExternalStorageDirectory()
- + «/Клипы/SOTY_ATHD.mp4» ));
- emailIntent.setType( «text/video» );
- // Поехали!
- SimpleEMail. this .startActivity(Intent.createChooser(emailIntent,
- «Отправка письма. » ));
- >
- >);
- >
- >
* 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) — Основной метод, в который передаются наши данные для отправки.
Рассмотрим код последнего метода чуть ближе:
- public synchronized void sendMail( String subject, String body, String sender, String recipients, String filename) throws Exception <
- try <
- MimeMessage message = new MimeMessage(session);
- // Кто
- message.setSender( new InternetAddress(sender));
- // О чем
- message.setSubject(subject);
- // Кому
- if (recipients.indexOf( ‘,’ ) > 0)
- message.setRecipients(Message.RecipientType.TO,
- InternetAddress.parse(recipients));
- else
- message.setRecipient(Message.RecipientType.TO,
- new InternetAddress(recipients));
- // Хочет сказать
- BodyPart messageBodyPart = new MimeBodyPart();
- messageBodyPart.setText(body);
- _multipart.addBodyPart(messageBodyPart);
- // И что показать
- if (!filename.equalsIgnoreCase( «» )) <
- BodyPart attachBodyPart = new MimeBodyPart();
- DataSource source = new FileDataSource(filename);
- attachBodyPart.setDataHandler( new DataHandler(source));
- attachBodyPart.setFileName(filename);
- _multipart.addBodyPart(attachBodyPart);
- >
- message.setContent(_multipart);
- Transport.send(message);
- > catch (Exception e) <
- Log.e( «sendMail» , «Ошибка отправки функцией sendMail! » );
- >
- >
* 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:
- private class sender_mail_async extends AsyncTask String , Boolean><
- ProgressDialog WaitingDialog;
- @Override
- protected void onPreExecute() <
- // Выводим пользователю процесс загрузки
- WaitingDialog = ProgressDialog.show(ExtendedMail. this , «Отправка данных» , «Отправляем сообщение. » , true );
- >
- @Override
- protected void onPostExecute(Boolean result) <
- // Прячем процесс загрузки
- WaitingDialog.dismiss();
- Toast.makeText(mainContext, «Отправка завершена. » , Toast.LENGTH_LONG).show();
- ((Activity)mainContext).finish();
- >
- @Override
- protected Boolean doInBackground(Object. params ) <
- try <
- // Получаем данные с наших полей
- title = ((EditText)findViewById(R.id.screen_sendnews_et_title)).getText().toString();
- text = ((EditText)findViewById(R.id.screen_sendnews_et_text)).getText().toString();
- from = «from_post_msg@gmail.com» ;
- where = «where_post_msg@yandex.ru» ;
- // Вызываем конструктор и передаём в него наши логин и пароль от ящика на gmail.com
- MailSenderClass sender = new MailSenderClass( «mypostmail@gmail.com» , «password» );
- // И вызываем наш метод отправки
- sender.sendMail(title, text, from , where , attach);
- > catch (Exception e) <
- Toast.makeText(mainContext, «Ошибка отправки сообщения!» , Toast.LENGTH_SHORT).show();
- >
- return false ;
- >
- >
* This source code was highlighted with Source Code Highlighter .
- public void onClick(View v) <
- sender_mail_async async_sending = new sender_mail_async();
- async_sending.execute();
- >
* This source code was highlighted with Source Code Highlighter .
Таким образом создав небольшой класс-поток, можно спокойно слать необходимую информацию от клиента к себе на ящик.
Источник
Send Mail in Android without Using Intent
Posted By : Ravi Sharma | 12-Aug-2013
Sending mail is one key feature in android and an easy one as well.
You may send mail using Intent as well but that requires user interface.
So, this blog will be useful to those who want to send mail in android as a background task without letting the user know.
Here is the xml file
Its a very basic layout with a button to send mail.
We will be using JavaMail Api to send the mail.For which you will be required to add three jars which you may download from here
https://code.google.com/p/javamail-android/downloads/list
The code involves three files
GMailSender.java
This is the file which is most important since this allows sending the mail, checking password authentication, adding attachments. It extends javax.mail.Authenticator, Properties class is used to declare port no to be used, protocol to be used (smtp) sendMail method sets the sender, recipients, body, subject, while addAttachment, attaches a file from sdcard.
JSSEProvider.java
This class is for security permissions so that SSL content may be handled. You dont need to modify it.
MainActivity.java
This class uses GMailSender class to set the sender email id, password.
using addAttachment method we specify path of file to be attached.
sendMail has four parameters namely subject, body text, senders name, recipients.
Add appropriate file path depending on device and a valid one.
The file size to be attached may be an issue since it depends on network so mail may be send later.
I have tested code for maximum of 2 MB .
also add internet permission to manifest file.
On clicking send mail button ,mail will be send along with attachment, refresh the page or wait for sometime to see the result.
Источник
Android — Sending Email
Email is messages distributed by electronic means from one system user to one or more recipients via a network.
Before starting Email Activity, You must know Email functionality with intent, Intent is carrying data from one component to another component with-in the application or outside the application.
To send an email from your application, you don’t have to implement an email client from the beginning, but you can use an existing one like the default Email app provided from Android, Gmail, Outlook, K-9 Mail etc. For this purpose, we need to write an Activity that launches an email client, using an implicit Intent with the right action and data. In this example, we are going to send an email from our app by using an Intent object that launches existing email clients.
Following section explains different parts of our Intent object required to send an email.
Intent Object — Action to send Email
You will use ACTION_SEND action to launch an email client installed on your Android device. Following is simple syntax to create an intent with ACTION_SEND action.
Intent Object — Data/Type to send Email
To send an email you need to specify mailto: as URI using setData() method and data type will be to text/plain using setType() method as follows −
Intent Object — Extra to send Email
Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be attached to the intent before sending the intent to a target email client. You can use following extra fields in your email −
Sr.No. | Extra Data & Description | |||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
Step | Description |
---|---|
1 | You will use Android studio to create an Android application and name it as Tutorialspoint under a package com.example.tutorialspoint. |
2 | Modify src/MainActivity.java file and add required code to take care of sending email. |
3 | Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I’m adding a simple button to launch Email Client. |
4 | Modify res/values/strings.xml to define required constant values |
5 | Modify AndroidManifest.xml as shown below |
6 | Run the application to launch Android emulator and verify the result of the changes done in the application. |
Following is the content of the modified main activity file src/com.example.Tutorialspoint/MainActivity.java.
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo
Following will be the content of res/values/strings.xml to define two new constants −
Following is the default content of AndroidManifest.xml −
Let’s try to run your tutorialspoint application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application.Select your mobile device as an option and then check your mobile device which will display following screen −
Now use Compose Email button to list down all the installed email clients. From the list, you can choose one of email clients to send your email. I’m going to use Gmail client to send my email which will have all the provided defaults fields available as shown below. Here From: will be default email ID you have registered for your Android device.
You can modify either of the given default fields and finally use send email button to send your email to the mentioned recipients.
Источник