【问题标题】:How to send an email with a file attachment in Android如何在 Android 中发送带有文件附件的电子邮件
【发布时间】:2012-04-16 00:40:42
【问题描述】:

我想在我的邮件中附加 .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);
}

【问题讨论】:

    标签: android email email-attachments vcf-vcard


    【解决方案1】:

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

    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..."));
    

    【讨论】:

    • 您不应使用“硬编码”路径,因为它们可能会因设备而异。我建议您将文件位置的定义更改为: File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);然后定义:Uri path = Uri.fromFile(filelocation);并将其放入您的意图中: emailIntent .putExtra(Intent.EXTRA_STREAM, path);
    • emailIntent.putExtra(Intent.EXTRA_STREAM, filelocation) 不会为我附加文件,而是使用 emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse( "file://"+filelocation) ) 菲利普工作得很好。
    • 如果文件尚未保存,这将如何工作?我将图像数据作为位图,但不是文件。在我们从文件中加载位图之前,您能否提供先保存位图的代码?
    【解决方案2】:

    官方Android site 上的示例对我有用。 所有需要它来添加

    startActivity(Intent.createChooser(emailIntent , "Send email..."));
    

    正如阿加瓦尔的回答中所做的那样

    【讨论】:

    • 在我的情况下,它会发送到邮件客户端但没有附件。显示的 toast 是“无法发送空文件”。我的文件存储在/data/data/com.example.app/files/temp.txt,我使用emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content:/"+filePath)); // filePath is /data/com.example.app/files/temp.txt 传递它
    • 您无法发送文件,因为它位于您应用的缓存目录中,并且只有您的应用可以从该目录中读取。您应该使用另一个目录,例如 Environment.getExternalStorageDirectory()。
    • 已使用 Environment.getExternalStorageDirectory(),验证路径有效且该文件具有良好数据....但仍然收到相同的错误消息 (?)。
    【解决方案3】:

    Folder_name 是手机内部存储中文件的名称。 (实际上是外部存储)。 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);
        }
    }
    

    【讨论】:

      【解决方案4】:

      SENDTO 不支持附件。我已经使用 Provider 添加了我的答案来读取文件信息。它在 Kotlin 中。

      fun shareFile(context: Context, filePath: File?, fileShareInfo: FileShareInfo) {
      
          val intentFileShare = Intent(Intent.ACTION_SEND)
      
          if (filePath!!.exists()) {
              intentFileShare.type = fileShareInfo.fileType
              val uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", filePath)
              intentFileShare.putExtra(Intent.EXTRA_STREAM, uri)
              fileShareInfo.recipients?.let {
                  intentFileShare.putExtra(Intent.EXTRA_EMAIL, fileShareInfo.recipients)
              }
              intentFileShare.putExtra(Intent.EXTRA_SUBJECT, fileShareInfo.shareSubjectText)
              fileShareInfo.shareExtraText?.let {
                  intentFileShare.putExtra(Intent.EXTRA_TEXT, AppViewUtil.fromHtml(fileShareInfo.shareExtraText!!))
              }
              try {
                  ContextCompat.startActivity(context, Intent.createChooser(intentFileShare, fileShareInfo.shareTitle), null)
              } catch (e: ActivityNotFoundException) {
                  Toast.makeText(context, context.getString(R.string.sharing_no_app_found), Toast.LENGTH_LONG).show()
              }
      
          }
      }
      

      【讨论】:

        【解决方案5】:

        我在 Kotlin 中编写了一个扩展程序,用于发送带有多个附件的电子邮件。我希望它对某人有用。

        fun AppCompatActivity.sendEmail(subject: String, content: String, email: String, fileAttachments: List<String> = emptyList()) {
        
            val emailIntent = Intent(Intent.ACTION_SEND_MULTIPLE).apply {
                type = "text/html"
                putExtra(Intent.EXTRA_SUBJECT, subject)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                putExtra(Intent.EXTRA_TEXT, content)
                putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
        
                // Configure attachments
                val attachments = fileAttachments.map { File(it) }.filter { it.exists() && !it.isDirectory }.map {
                    FileProvider.getUriForFile(baseContext, "${BuildConfig.APPLICATION_ID}.fileprovider", it)
                }.toList()
        
                if(attachments.isNotEmpty())
                    putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(attachments))
            }
        
            if (emailIntent.resolveActivity(packageManager) != null)
                startActivity(Intent.createChooser(emailIntent, "Chooser Mail Client"))
        }
        

        【讨论】:

          猜你喜欢
          • 2012-03-24
          • 1970-01-01
          • 2012-06-15
          • 2015-09-09
          • 2017-09-06
          • 1970-01-01
          相关资源
          最近更新 更多