Html email from android

The Code City

Search This Blog

Send Email from Android App directly without Intent

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

Sending Email from an Android app is not difficult if you want to open up another Email App that handles sending the Email. We can just achieve that by adding an ACTION_SEND intent and we can also set content type and use extras such as EXTRA_EMAIL, EXTRA_CC and more. If we start this intent, all the apps that can handle emails such as Gmail app, default Email app will be shown in a chooser dialog if you haven’t chosen a default already. Then your user can easily manage the creation and sending of the email from the third party app. But that’s not always the case, some times we are required to send an Email from our own App with a fixed Email address to a specific Email address, for example if we need to send a password recovery link on the click of Forgot Password, recovery link to the user should be sent by email from within our app with our own Email Address. In this post we will learn how we can send Email directly from an Android App without and Intent. So let us begin.

Screenshot of final App of this tutorial

Steps in sending Email from Android App directly without Intent:

We require 3 jar libraries for allowing us to send Emails, download the three libraries (LINK BELOW)
We create a JSSEProvider class.
We create a MailSender class that handles Authentication for our Email and sends Email directly without intent.

So now that we have the steps laid out, let’s dig deeper on how to send Email Directly form our App, here’s a sample video of the Email app that we will create:

Step 1
First of all download the 3 files- Activation.jar, Additional.jar, Mail.jar.
These are libraries that allow us to send Email in Java.
Once you’ve downloaded theses files, put it in the libs folder inside your app directory. If you don’t have a libs folder inside your app folder, create one and place these files inside the folder.

Step 2
Now that you’ve copied the files in libs directory, it’s time to include those libraries as dependencies. You’ll need to do some changes in the app level Gradle file. Add the following lines in you dependencies section:

Читайте также:  Android color with alpha

compile files(‘libs/activation.jar’)
compile files(‘libs/additional.jar’)
compile files(‘libs/mail.jar’)

Now you are done with libraries part and are ready to code the Email Sender App.

Step 3
Create a new class called JSSEProvider it should extend Provider class. JSSE provides a framework and an implementation for the SSL and TLS security and also provides some other functionalities like encryption and more. You can learn more about it here. Now add the following code in the class. Import all the required classes:

public JSSEProvider() <
super(«HarmonyJSSE», 1.0, «Harmony JSSE Provider»);
AccessController.doPrivileged(new java.security.PrivilegedAction () <
public Void run() <
put(«SSLContext.TLS»,
«org.apache.harmony.xnet.provider.jsse.SSLContextImpl»);
put(«Alg.Alias.SSLContext.TLSv1», «TLS»);
put(«KeyManagerFactory.X509»,
«org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl»);
put(«TrustManagerFactory.X509»,
«org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl»);
return null;
>
>);
>

Step 4
Create a class that extends javax.mail.Authentication. I’ve called it Gmail Sender because I’ll be sending Email from one of my Gmail account. Now add the following code in the class:

private String mailhost = «smtp.gmail.com»;
private String user;
private String password;
private Session session;

static <
Security.addProvider(new JSSEProvider());
>

public GMailSender(String user, String password) <
this.user = user;
this.password = password;

Properties props = new Properties();
props.setProperty(«mail.transport.protocol», «smtp»);
props.setProperty(«mail.host», mailhost);
props.put(«mail.smtp.auth», «true»);
props.put(«mail.smtp.port», «465»);
props.put(«mail.smtp.socketFactory.port», «465»);
props.put(«mail.smtp.socketFactory.class»,
«javax.net.ssl.SSLSocketFactory»);
props.put(«mail.smtp.socketFactory.fallback», «false»);
props.setProperty(«mail.smtp.quitwait», «false»);

session = Session.getDefaultInstance(props, this);
>

protected PasswordAuthentication getPasswordAuthentication() <
return new PasswordAuthentication(user, password);
>

public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception <
try <
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), «text/plain»));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(‘,’) > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
>catch(Exception e) <
Log.d(«mylog», «Error in sending: » + e.toString());
>
>

public class ByteArrayDataSource implements DataSource <
private byte[] data;
private String type;

public ByteArrayDataSource(byte[] data, String type) <
super();
this.data = data;
this.type = type;
>

public ByteArrayDataSource(byte[] data) <
super();
this.data = data;
>

public void setType(String type) <
this.type = type;
>

public String getContentType() <
if (type == null)
return «application/octet-stream»;
else
return type;
>

public InputStream getInputStream() throws IOException <
return new ByteArrayInputStream(data);
>

public String getName() <
return «ByteArrayDataSource»;
>

public OutputStream getOutputStream() throws IOException <
throw new IOException(«Not Supported»);
>
>

Now we have all the required this are we are ready to send Email from our app. We will just create one method in our Activity and call it whenever we need to send the Email to the User. This method will contain your Email Address, your password so you can be authenticated and the email address of your recipient. Let’s call this methods sendMessage():

private void sendMessage() <
final ProgressDialog dialog = new ProgressDialog(ActivityMain.this);
dialog.setTitle(«Sending Email»);
dialog.setMessage(«Please wait»);
dialog.show();
Thread sender = new Thread(new Runnable() <
@Override
public void run() <
try <
GMailSender sender = new GMailSender(«youremail», «yourpassword»);
sender.sendMail(«EmailSender App»,
«This is the message body»,
«youremail»,
«your recipient’s email»);
dialog.dismiss();
> catch (Exception e) <
Log.e(«mylog», «Error: » + e.getMessage());
>
>
>);
sender.start();
>

Читайте также:  Живые обои танцующего андроид

Finally we have our app ready and we can call this method whenever we need to send the Email directly from the app without any intents. You can find the full source code below, Cheers!

NOTE: Gmail has disabled logging in to accounts by third party apps. You need to disable this feature of Gmail and allow logging in from any app otherwise you won’t be able to login and Emails won’t be sent from your account.

Full source code for Email Sender App:Download Email Sender

Источник

Отправка 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) — Основной метод, в который передаются наши данные для отправки.
Читайте также:  Roll the ball для андроид

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

  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 .

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

Источник

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