萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 呼叫系統 Email 應用發送郵件:無附件、單附件、多附件完整實作

Android 透過 Intent 呼叫系統或第三方 Email 客戶端發送郵件,三種 Action 對應不同附件需求:

  • ACTION_SENDTO:無附件,僅郵件地址、主旨、內文。
  • ACTION_SEND:單一附件。
  • ACTION_SEND_MULTIPLE:多附件。

系統會彈出選擇器讓用戶挑選郵件客戶端(Gmail、Outlook、預設 Email 等)。

1. 無附件發送 (ACTION_SENDTO)

Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:455245521@qq.com"));
intent.putExtra(Intent.EXTRA_SUBJECT, "這是標題");
intent.putExtra(Intent.EXTRA_TEXT, "這是內容");
startActivity(intent);

2. 單附件發送 (ACTION_SEND)

Intent intent = new Intent(Intent.ACTION_SEND);
String[] tos = {"fdafdafa@gmail.com"};
String[] ccs = {"gegeff@gmail.com"};
String[] bccs = {"fdafda@gmail.com"};

intent.putExtra(Intent.EXTRA_EMAIL, tos);      // 收件者
intent.putExtra(Intent.EXTRA_CC, ccs);         // 副本
intent.putExtra(Intent.EXTRA_BCC, bccs);       // 密件副本
intent.putExtra(Intent.EXTRA_TEXT, "body");    // 內文
intent.putExtra(Intent.EXTRA_SUBJECT, "subject"); // 主旨
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/Chrysanthemum.jpg")); // 附件 URI
intent.setType("image/*");                     // MIME 類型
// intent.setType("message/rfc822");           // 或郵件標準類型
startActivity(Intent.createChooser(intent, "Choose Email Client"));

3. 多附件發送 (ACTION_SEND_MULTIPLE)

Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
String[] tos = {"wingfourever@gmail.com"};
String[] ccs = {"tongyue@gmail.com"};

intent.putExtra(Intent.EXTRA_EMAIL, tos);
intent.putExtra(Intent.EXTRA_CC, ccs);
intent.putExtra(Intent.EXTRA_TEXT, "body");
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");

// 多附件 URI 列表
ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(Uri.parse("file:///sdcard/Chrysanthemum.jpg"));
imageUris.add(Uri.parse("file:///sdcard/Desert.jpg"));
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris); // 關鍵:Parcelable ArrayList

intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Choose Email Client"));

關鍵差異總結

Action附件方式MIME 類型範例
ACTION_SENDTO無附件,mailto: URI不需 setType
ACTION_SENDEXTRA_STREAM (單一 Uri)image/*, message/rfc822
ACTION_SEND_MULTIPLEEXTRA_STREAM (ArrayList<Uri>)image/*, message/rfc822

注意: Android 7.0+ (API 24) 強制使用 FileProvider 產生 content:// URI 替代 file://,否則會拋出 FileUriExposedException。實際專案請配合 FileProvider 實作安全分享。

copyright © 萬盛學電腦網 all rights reserved