Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 透過 Intent 發送帶附件的電子郵件

編輯:初階開發

如何在 Android 系統中發送帶附件的電子郵件?其實借助 Intent 就能輕鬆實現,短短十行代碼即可搞定。下面以 SD 卡上的 android123.cwj 檔案為例,示範如何透過 Intent 發送帶附件的郵件。完整代碼如下:

File file = new File("/sdcard/android123.cwj"); //附件文件地址

  Intent intent = new Intent(Intent.ACTION_SEND);
  intent.putExtra("subject", file.getName());
  intent.putExtra("body", "android123 - email sender"); //正文
  intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); //添加附件,附件為file對象
             if (file.getName().endsWith(".gz")) {
                 intent.setType("application/x-gzip"); //如果是gz使用gzip的mime
             } else if (file.getName().endsWith(".txt")) {
                 intent.setType("text/plain"); //純文本則用text/plain的mime
             } else {
                 intent.setType("application/octet-stream"); //其他的均使用流當做二進制數據來發送
             }
  startActivity(intent); //調用系統的mail客戶端進行發送

這段代碼的巧妙之處在於根據附件的副檔名動態設置 MIME 類型:gz 檔案用 application/x-gzip,純文本用 text/plain,其餘則統一按二進制流 application/octet-stream 處理。透過 Intent.ACTION_SEND 搭配 EXTRA_STREAM,就能調起系統郵件客戶端完成發送,既簡潔又實用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved