Follow treslines by email clicking Here!

Wednesday, August 6, 2014

How to send email with attachment over android and how to import files from download folder

Hi there!

Today i'm gonna show how to attach a file as attachment and send it over your smartphone using Android. This is specially good if you want users to send you feedbacks or you are trying to backup something.

I had specially problems with attachments because out there was a lot of content but no one completed. Just code snippets and fragments. Here you'll find a complete and working example!


Preparing Attachments

Before you can send attachments, you must create a file in an external directory of your choice before trying to send it. I tryed several approaches and no one has worked for me. Only this one! So, first of all save your data, for example, like this bellow:

    private static final String DATABASE_NAME = "yourDatabaseName.db";
    private static final String SEPARATOR = File.separator;
    public static final String BACKUP = SEPARATOR+DATABASE_NAME;
    public final String packageName = context.getPackageName();
    public static final String DB_FILEPATH = "/data/data/" + packageName + "/databases/"+DATABASE_NAME;
 
    public void backupDatabase() throws IOException {

        if (isSDCardWriteable()) {
            // Open your local db as the input stream
            String inFileName = DB_FILEPATH;
            File dbFile = new File(inFileName);
            FileInputStream fis = new FileInputStream(dbFile);

            String outFileName = Environment.getExternalStorageDirectory()+ BACKUP;
            // Open the empty db as the output stream
            OutputStream output = new FileOutputStream(outFileName);
            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            // Close the streams
            output.flush();
            output.close();
            fis.close();
        }
    }
    

    private boolean isSDCardWriteable() {
        boolean rc = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            rc = true;
        }
        return rc;
    }

Email Intent

Das is the method responsible for sending emails.

    public void backupOverEmail(String[] toEmails) throws IOException {
        backupDatabase();
        String fileName = BACKUP;
        File file = new File(Environment.getExternalStorageDirectory() + fileName);
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("application/octet-stream");
        intent.putExtra(Intent.EXTRA_SUBJECT, "Backup");
        intent.putExtra(Intent.EXTRA_EMAIL, toEmails);
        intent.putExtra(Intent.EXTRA_TEXT, "Backup database\n");
        intent.putExtra(Intent.EXTRA_STREAM, path);
        context.startActivity(Intent.createChooser(intent, "Send mail..."));
    }

Importing Files 

To import your files, you may use this:

    public void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {
            fromChannel = fromFile.getChannel();
            toChannel = toFile.getChannel();
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } finally {
            try {
                if (fromChannel != null) {
                    fromChannel.close();
                }
            } finally {
                if (toChannel != null) {
                    toChannel.close();
                }
            }
        }
    }
    public boolean importDatabase() throws IOException {

        // import backup from download folder
        String dbPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + BACKUP;
        // Close the SQLiteOpenHelper so it will
        // commit the created empty database to internal storage.
        close();
        File newDb = new File(dbPath);
        File oldDb = new File(DB_FILEPATH);
        if (newDb.exists()) {
            copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
            // Access the copied database so SQLiteHelper
            // will cache it and mark it as created.
            getWritableDatabase().close();
            return true;
        }
        return false;
    }

That's alll. Hope you like it.

No comments:

Post a Comment