Cómo adjuntar archivo PDF de los activos en el correo electrónico?

Cómo adjuntar archivo pdf de los activos en el correo electrónico en mi aplicación? Estoy utilizando el siguiente código para asignar la imagen, pero no sé cómo adjuntar pdf.

Archivo EMail.Java

 Paquete com.drc.email;

 Import android.app.Activity;
 Import android.content.Intent;
 Import android.database.Cursor;
 Import android.net.Uri;
 Import android.os.Bundle;
 Import android.provider.MediaStore;
 Import android.util.Log;
 Import android.view.View;
 Import android.view.View.OnClickListener;
 Import android.widget.Button;
 Import android.widget.EditText;
 Import android.widget.Toast;

 Public class Email extends Actividad {
     Botón enviar, adjuntar;
     EditText userid, contraseña, de, a, sujeto, cuerpo;

     Private static final int SELECT_PICTURE = 1;
     Private String selectedImagePath = null;

     /** Se llama cuando se crea por primera vez la actividad.  * /
     @Anular
     Public void onCreate (Bundle savedInstanceState) {
         Super.onCreate (savedInstanceState);
         SetContentView (R.layout.main);

         Enviar = (Botón) this.findViewById (R.id.btnsend);
         Attach = (Button) this.findViewById (R.id.btnattach);
         Userid = (EditText) this.findViewById (R.id.userid);
         Password = (EditText) this.findViewById (R.id.password);
         From = (EditText) this.findViewById (R.id.from);
         To = (EditText) this.findViewById (R.id.to);
         Subject = (EditText) this.findViewById (R.id.subject);
         Body = (EditText) this.findViewById (R.id.body);
         Attach.setOnClickListener (nuevo OnClickListener () {

             @Anular
             Public void onClick (Ver v) {
                 // Método generado automáticamente TODO talón
                   // seleccione un archivo
                 SelectedImagePath = null;
                 Intención intención = nueva Intención ();
                 Intent.setType ("image / *");
                 Intent.setAction (Intent.ACTION_GET_CONTENT);
                 StartActivityForResult (Intent.createChooser (intención, "Seleccionar imagen"), SELECT_PICTURE);
             }
         });
         Send.setOnClickListener (new View.OnClickListener () {

             Public void onClick (Ver vista) {
                 MailSender sender = nuevo MailSender (userid.getText (). ToString (), password.getText (). ToString ());
                 tratar {
                     If (selectedImagePath == null)
                     {
                          Sender.sendMail (subject.getText (). ToString (), body.getText (). ToString (), from.getText (). ToString (), to.getText (). ToString ());
                          Toast.makeText (getBaseContext (), "Send Mail Sucess", Toast.LENGTH_LONG) .show ();
                     }
                     más
                     {
                      (), ToString (), selectedImagePath.toString (), to.Text (), to.Text (), to.Control () String.format ("image% d.jpeg", System.currentTimeMillis ()));
                      Toast.makeText (getBaseContext (), "Enviar Attach Mail Sucess", Toast.LENGTH_LONG) .show ();
                     }
                 } Catch (Excepción e) {
                     Log.e ("SendMail", e.getMessage (), e);

                 }
                 Sender = null;

             }

         });

     }
     Public void onActivityResult (int requestCode, int resultCode, datos de intención) {
         If (resultCode == RESULT_OK) {
             If (requestCode == SELECT_PICTURE) {
                 Uri selectedImageUri = data.getData ();
                 SelectedImagePath = getPath (selectedImageUri);
                 //disimage.setImageURI(Uri.parse(selectedImagePath));
             }
         }
     }
     Public String getPath (Uri uri) {
         String [] projection = {MediaStore.Images.Media.DATA};
         Cursor cursor = managedQuery (uri, proyección, nulo, nulo, nulo);
         Int column_index = cursor.getColumnIndexOrThrow (MediaStore.Images.Media.DATA);
         Cursor.moveToFirst ();
      // Toast.makeText (esto, cursor.getString (column_index) .toString (), Toast.LENGTH_LONG);
         Return cursor.getString (column_index);
     }
 }

Archivo MailSender.java: –

 Paquete com.drc.email;

 Import javax.activation.DataHandler;
 Import javax.activation.DataSource;
 Import javax.activation.FileDataSource;
 Import javax.mail.Message;
 Import javax.mail.Multipart;
 Import javax.mail.PasswordAuthentication;
 Import javax.mail.Session;
 Import javax.mail.Transport;
 Import javax.mail.internet.InternetAddress;
 Import javax.mail.internet.MimeBodyPart;
 Import javax.mail.internet.MimeMessage;
 Import javax.mail.internet.MimeMultipart;

 Import java.io.ByteArrayInputStream;
 Import java.io.IOException;
 Import java.io.InputStream;
 Import java.io.OutputStream;
 Import java.util.Properties;

 Public class MailSender extends javax.mail.Authenticator {

     Cadena privada mailhost = "smtp.gmail.com";
     Private String usuario;
     Private String contraseña;
     Sesión de sesión privada;

     Estática {
         // Security.addProvider (new
         // org.apache.harmony.xnet.provider.jsse.JSSEProvider ());
     }

     Public MailSender (String user, String password) {
         This.user = usuario;
         This.password = contraseña;
         System.out.println ("Hola");
         Propiedades Propiedades = Propiedades nuevas ();
         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 (apoyos, esto);
     }

     Protected PasswordAuthentication getPasswordAuthentication () {
         Return nuevo PasswordAuthentication (usuario, contraseña);
     }

     Public synchronized void sendMail (String subject, String body, String sender, String destinatarios) throws Exception {
         MimeMessage message = new MimeMessage (sesión);
         DataHandler handler = nuevo DataHandler (nuevo ByteArrayDataSource (body.getBytes (), "text / plain"));
         Message.setSender (nuevo InternetAddress (remitente));
         Message.setSubject (subject);
         Message.setDataHandler (handler);
         If (recipients.indexOf (',')> 0)
             Message.setRecipients (Message.RecipientType.TO, InternetAddress.parse (destinatarios));
         más
             Message.setRecipient (Message.RecipientType.TO, nuevo InternetAddress (destinatarios));

         Transport.send (mensaje);
     }
     Public synchronized void sendMailAttach (String subject, String body, String sender, String destinatarios, String selectedImagePath, String nombre de archivo) throws Exception {
         MimeMessage message = new MimeMessage (sesión);
         Message.setSender (nuevo InternetAddress (remitente));
         Message.setSubject (subject);
             // Establece el texto del mensaje de correo electrónico.
             //
             MimeBodyPart messagePart = new MimeBodyPart ();
             MessagePart.setText (body);
             //
             // Establecer el archivo adjunto de correo electrónico
             //
             MimeBodyPart attachmentPart = new MimeBodyPart ();
             FileDataSource fileDataSource = nuevo FileDataSource (selectedImagePath) {
                 @Anular
                 Public String getContentType () {
                 Return "application / octet-stream";
                 }
             };
             AttachmentPart.setDataHandler (nuevo DataHandler (fileDataSource));
             AttachmentPart.setFileName (nombre de archivo);

             Multipart multipart = nuevo MimeMultipart ();
             Multipart.addBodyPart (messagePart);
             Multipart.addBodyPart (attachmentPart);

             Message.setContent (multipart);

         If (recipients.indexOf (',')> 0)
             {Message.setRecipients (Message.RecipientType.TO, InternetAddress.parse (destinatarios));}
         más
             {Message.setRecipient (Message.RecipientType.TO, new InternetAddress (destinatarios));}

         Transport.send (mensaje);
     }
     Public class ByteArrayDataSource implementa DataSource {
         Datos de byte privado [];
         Privado Tipo de cadena;

         Public ByteArrayDataSource (byte [] data, Tipo de cadena) {
             súper();
             This.data = data;
             This.type = tipo;
         }

         Public ByteArrayDataSource (datos de byte []) {
             súper();
             This.data = data;
         }

         Public void setType (Tipo de cadena) {
             This.type = tipo;
         }

         Public String getContentType () {
             If (type == null)
                 Return "application / octet-stream";
             más
                 Tipo de devolución;
         }

         Public InputStream getInputStream () lanza IOException {
             Return new ByteArrayInputStream (datos);
         }

         Public String getName () {
             Return "ByteArrayDataSource";
         }

         Public OutputStream getOutputStream () lanza IOException {
             Throw nuevo IOException ("Not Supported");
         }
     }
 }

Aquí estoy uso 3 archivos jar externos.

1) activation.jar 2) additional.jar 3) mail.jar

Debería estar haciendo referencia al archivo PDF myfile.pdf en el directorio de activos usando URI como:

Uri uri=Uri.parse("file:///android_asset/myfile.pdf"); 
 i've done for send any file from SD card with mail attachment.. Intent sendEmail= new Intent(Intent.ACTION_SEND); sendEmail.setType("rar/image"); sendEmail.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/mnt/sdcard/download/abc.rar"))); startActivity(Intent.createChooser(sendEmail, "Email:")); 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.