如何在Android中发送包含文件附件的电子邮件

Nar*_*rma 47 email android vcf email-attachments

我想在我的邮件中附上.vcf文件并通过邮件发送.但邮件收到的地址没有附件.我使用下面的代码,但代码为此,我不知道我错在哪里.

try {      
  String filelocation="/mnt/sdcard/contacts_sid.vcf";      
  Intent intent = new Intent(Intent.ACTION_SENDTO);    
  intent.setType("text/plain");      
  intent.putExtra(Intent.EXTRA_SUBJECT, "");      
  intent.putExtra(Intent.EXTRA_STREAM, Uri.parse( "file://"+filelocation));      
  intent.putExtra(Intent.EXTRA_TEXT, message);         
  intent.setData(Uri.parse("mailto:"));         
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

  activity.startActivity(intent);
  activity.finish();
  } catch(Exception e)  {
     System.out.println("is exception raises during sending mail"+e);
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*wal 87

使用以下代码在电子邮件中发送文件.

String filename="contacts_sid.vcf"; 
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
Uri path = Uri.fromFile(filelocation); 
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"asd@gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(emailIntent , "Send email..."));
Run Code Online (Sandbox Code Playgroud)

  • 您不应使用"硬编码"路径,因为它们可能会因设备而异.我建议你将filelocation的定义更改为:file filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),filename); 然后定义:Uri path = Uri.fromFile(filelocation); 并把它放在你的意图:emailIntent .putExtra(Intent.EXTRA_STREAM,path); (3认同)

小智 10

Folder_name是手机内部存储中文件的名称.(实际上是EXTERNAL_STORAGE).file_name是要发送的文件的名称.

private void ShareViaEmail(String folder_name, String file_name) {
    try {
        File root= Environment.getExternalStorageDirectory();
        String filelocation= root.getAbsolutePath() + folder_name + "/" + file_name;
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setType("text/plain");
        String message="File to be shared is " + file_name + ".";
        intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
        intent.putExtra(Intent.EXTRA_STREAM, Uri.parse( "file://"+filelocation));
        intent.putExtra(Intent.EXTRA_TEXT, message);
        intent.setData(Uri.parse("mailto:xyz@gmail.com"));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        startActivity(intent);
    } catch(Exception e)  {
        System.out.println("is exception raises during sending mail"+e);
    }
}
Run Code Online (Sandbox Code Playgroud)