Android – How to attach pdf file from assets in email

androidandroid-assets

How do I attach pdf file from assets to email in my application? I am using following code to attach image but I don't know how to attach pdf.

EMail.java file

package 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 Activity {
    Button send,attach;
    EditText userid,password,from,to,subject,body;

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

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        send = (Button) 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(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                  // select a file
                selectedImagePath=null;
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
            }
        });
        send.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                MailSender sender = new MailSender(userid.getText().toString(), password.getText().toString());
                try {
                    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();
                    }
                    else
                    {
                     sender.sendMailAttach(subject.getText().toString(), body.getText().toString(), from.getText().toString(),to.getText().toString(),selectedImagePath.toString(),String.format("image%d.jpeg", System.currentTimeMillis()));
                     Toast.makeText(getBaseContext(),  "Send Attach Mail Sucess", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Log.e("SendMail", e.getMessage(), e);

                }
                sender=null;

            }

        });

    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        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, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
     //   Toast.makeText(this,cursor.getString(column_index).toString(), Toast.LENGTH_LONG);
        return cursor.getString(column_index);
    }
}

MailSender.java file

package 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 {

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

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

    public MailSender(String user, String password) {
        this.user = user;
        this.password = password;
        System.out.println("Hello");
        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 {
        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);
    }
    public synchronized void sendMailAttach(String subject, String body,String sender, String recipients, String selectedImagePath,String filename) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setSender(new InternetAddress(sender));
        message.setSubject(subject);
            // Set the email message text.
            //
            MimeBodyPart messagePart = new MimeBodyPart();
            messagePart.setText(body);
            //
            // Set the email attachment file
            //
            MimeBodyPart attachmentPart = new MimeBodyPart();
            FileDataSource fileDataSource = new FileDataSource(selectedImagePath) {
                @Override
                public String getContentType() {
                return "application/octet-stream";
                }
            };
            attachmentPart.setDataHandler(new DataHandler(fileDataSource));
            attachmentPart.setFileName(filename);

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

            message.setContent(multipart);

        if (recipients.indexOf(',') > 0)
            {message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));}
        else
            {message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));}

        Transport.send(message);
    }
    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");
        }
    }
}

I am using 3 external jar files.

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

Best Answer

You should be referencing to PDF file myfile.pdf in asset directory using URI like:

Uri uri=Uri.parse("file:///android_asset/myfile.pdf"); 
Related Topic