简体   繁体   中英

How to attach file to email? - android

I try to attach a file to an email. The user writes to the file. When he is done, the file is saved on internal storage and should be sent by e-mail.

Here is the code:

// write text to file
public void WriteBtn(View v) {
    // add-write text into file
    try {
        FileOutputStream fileout = openFileOutput(fileName, MODE_PRIVATE);
        OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
        outputWriter.write(textmsg.getText().toString());
        outputWriter.close();
        fileout.close();
        String fileLocation= Environment.getDataDirectory()+"/"+fileName;
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        // set the type to 'email'
        emailIntent .setType("vnd.android.cursor.dir/email");
        String to[] = {"oshrat0207@gmail.com"};
        emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
        // the attachment
        emailIntent .putExtra(Intent.EXTRA_STREAM, fileLocation);
        // the mail subject
        emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
       // Uri uri = Uri.fromFile(new File(fileLocation));
        String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
        Uri uri = Uri.fromFile(new File(sdCard +
                new String(new char[sdCard.replaceAll("[^/]", "").length()])
                        .replace("\0", "/..") + getFilesDir() + "/" + fileName));
        emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(emailIntent , "Send email..."));

        //display file saved message
        Toast.makeText(getBaseContext(), "File saved successfully! path:" + fileLocation,
                Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

The Exceptions:

  1. close() was never explicitly called on database '/data/data/com.google.android.gms/databases/phenotype.db' android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

  2. Error finding the version of the Email provider.....

  3. ctivity com.android.internal.app.ChooserActivity has leaked IntentReceiver com.android.internal.app.ResolverActivity$1@4107d478 that was originally registered here. Are you missing a call to unregisterReceiver()? android.app.IntentReceiverLeaked: Activity com.android.internal.app.ChooserActivity has leaked IntentReceiver com.android.internal.app.ResolverActivity$1@4107d478 that was originally registered here. Are you missing a call to unregisterReceiver()?

What am I doing wrong?

You can use JavaMail API to send multipart emails which can attach files to an email. For sending the email using JavaMail API, you need to load the two jar files:

mail.jar activation.jar

You can go to the Oracle site to download the latest version.

Check the example below

public MimeMessage createEmailMessage() throws AddressException,
MessagingException, UnsupportedEncodingException {

Session mailSession;
MimeMessage emailMessage;

    File csvFile = new File(csvFilePath);
    if(null != csvFile.list()){
        csvName = (csvFile.list())[0];
    }

    if(null != csvName ){

        mailSession = Session.getDefaultInstance(emailProperties, null);
        emailMessage = new MimeMessage(mailSession);

        emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
        emailMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(toEmail));

        emailMessage.setSubject(emailSubject);
        //emailMessage.setContent(emailBody, "text/html");// for a html email


        // creates message part
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        //          messageBodyPart.setContent(message, "text/html");

        // creates multi-part
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        File csvDir = new File(Constant.FilePathConstant.CSV_PATH );

        /***** attach csv files *****/
        if(csvDir.exists()){
            File[] csvList = xlsDir.listFiles();
            for (File file : csvList) {
                MimeBodyPart attachPart = new MimeBodyPart();
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@ csv " + file.getAbsolutePath());
                try{
                    attachPart.attachFile(file.getAbsolutePath());
                }catch(Exception e){
                    e.printStackTrace();
                }
                multipart.addBodyPart(attachPart);
            }
        }


        // sets the multi-part as e-mail's content
        emailMessage.setContent(multipart);

         emailMessage.setText(emailBody);
        Logger.i("GMail", "Email Message created.");
    }
    return emailMessage;
}

public boolean sendEmail() throws AddressException, MessagingException {
    if(null != emailMessage){
        Transport transport = mailSession.getTransport("smtp");
        transport.connect(emailHost, fromEmail, fromPassword);
        transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
        transport.close();
        Logger.i("Report", "Email sent successfully.");
        return true;
    }else{
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM