- Отправка E-Mail средствами Android
- Часть 1. Mail, просто Mail
- Часть 2. Mail, анонимус Mail
- Android: Sending Email using Intents
- ACTION_SENDTO
- EmailIntentBuilder — Making life easier
- What about Attachments?
- Android Send Email with Examples
- Android Send Email Example
- activity_main.xml
- MainActivity.java
- AndroidManifest.xml
- Output of Android Send Email Example
Отправка 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 .
Таким образом создав небольшой класс-поток, можно спокойно слать необходимую информацию от клиента к себе на ящик.
Источник
Android: Sending Email using Intents
Jan 8, 2016 · 3 min read
Many things on Android are as easy as starting an Activity using the right Intent. Sending an email to a specific recipient is one of those things.
Sadly, there is much bad advice out there on how to send emails using Intents. Because I write an open source email app I have a pretty good understanding of what goes on behind the scenes. That’s why I believe I know better than all those other people 🙂
ACTION_SENDTO
To start the Activity to compose an email in your user’s favorite email app you use an Intent with the ACTION_SENDTO action. Unfortunately, the documentation is very sparse. It simply states:
Activity Action: Send a message to someone specified by the data.
Input: getData() is URI describing the target.
This doesn’t mention email at all because ACTION_SENDTO is very generic and can also be used to send e.g. SMS, MMS or XMPP messages.
To send an email we have to use a mailto URI as defined by RFC 6068. In its simplest form such a URI consists of “mailto:” followed by an email address, e.g. mailto:alice@example.org. You might recognize this syntax from email links in HTML documents.
Creating such an Intent might look like this:
Most of the time you want to provide more data than just a recipient. And the mailto specification allows us to also specify CC and BCC recipients, a subject, and even text for the email body.
Generating such a mailto URI is a bit tedious because you have to percent-encode certain characters as you can see in the example above.
Android’s Uri.Builder class would be the perfect fit since it makes it easy to add query parameters while taking care of the encoding. Unfortunately, building Uri instances doesn’t work very well for non-hierarchical URIs like mailto URIs. One way to work around that is to manually construct the URI and dealing with the encoding.
Some code samples advocate the use of EXTRA_SUBJECT, EXTRA_TEXT, etc. Those are certainly easier to use. However, the Android API reference only mentions them in connection with ACTION_SEND and ACTION_SEND_MULTIPLE. Those are more general Intents for sharing content to nobody in particular.
The fact that the Extras also work with ACTION_SENDTO was an undocumented “feature” of AOSP Email and the Gmail app. That functionality then had to be copied by all other Android email clients because apps were and are using those Extras.
But since all major email clients support the use of query parameters in mailto URIs I see no reason to use an undocumented feature and advice against it.
It is also worth mentioning that you shouldn’t use Intent.createChooser() to launch an email Intent. Users most likely have a preferred email app that they want to be able to select as default app. The standard behavior when resolving an Intent deals with that just fine.
There are a couple of other things that need to be considered. Line breaks in the body, for example, need to be encoded as %0D%0A (CRLF).
Because it’s no fun to deal with all of that when all you want to do is send an email, I wrote a small library to take care of the dirty details for you.
EmailIntentBuilder — Making life easier
The goal of the Email Intent Builder library is to make creating email Intents as easy as possible.
You can find it on Maven Central, the source code on GitHub.
Building an email Intent is a simple matter of calling some methods on the builder:
Most of the time you also want to launch the Intent. The start() method will do that for you while also taking care of not throwing an exception if no app could be found to handle the Intent.
What about Attachments?
Unfortunately, the ACTION_SENDTO Intent doesn’t support attachments. If you need to send an email containing one or more attachments you should use Android’s more generic share mechanism, i.e. ACTION_SEND or ACTION_SEND_MULTIPLE.
A lot of people have realized that this leads to quite a few more than just email apps showing up in the app chooser dialog. How to properly deal with that is material for another post.
I’d love to hear about your experiences dealing with email on Android. Let me know on Twitter.
Источник
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.
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.
Источник