iOS 開発 — メールを送る

Nov 26 2022
電子メールは、21 世紀における最高のコミュニケーション チャネルの 1 つです。情報は数秒で受信者のグループに配信できます。

電子メールは、21 世紀における最高のコミュニケーション チャネルの 1 つです。情報は数秒で受信者のグループに配信できます。メール機能をアプリに統合することを考えたことはありますか?

Apple は、使いやすいフレームワークMessageUIを開発者向けに提供しています。次のプロパティを構成できます。

  1. 受信者リスト
  2. 主題
  3. メッセージ本文
  4. 付属品

ステップバイステップの手順

ステップ 1) デバイスがメールを送信できるかどうかを確認する

import MessageUI

// Confirm the user can send email
guard MFMailComposeViewController.canSendMail() else { return }

1. アプリ ユーザーは、システム メーリング アプリで自分のメール アカウントをまだ設定していません。

2. iOS MDM プロファイルは、このStackOverflowの回答を参照して、メール機能を無効にしました。

手順 2) MFMailComposeViewController インスタンスを構成する

// Construct the `MFMailComposeViewController` instance
let mfMailComposeViewController = MFMailComposeViewController()

// To set the recipients list, including the to, cc and bcc fields
mfMailComposeViewController.setToRecipients(["[email protected]"])
mfMailComposeViewController.setCcRecipients(["[email protected]"])
mfMailComposeViewController.setBccRecipients(["[email protected]"])

// To set the email subject
mfMailComposeViewController.setSubject("Example - Subject Text")

// To set the email message body; It can be either plain text or HTML message
mfMailComposeViewController.setMessageBody("<h1>Example - HTML message body </h1>", isHTML: true)

// Presenet the `MFMailComposeViewController` to the app user
present(mfMailComposeViewController, animated: true)

  1. to, cc&を含む受信者のリストbcc
  2. 対象分野
  3. プレーン テキストまたはHTML メッセージのメッセージ本文

手順 3) MFMailComposeViewController を手動で閉じる

// We must implement the `MFMailComposeViewControllerDelegate` in order to handle the user's action on the mail compo
mfMailComposeViewController.mailComposeDelegate = self

extension DemoViewController: MFMailComposeViewControllerDelegate {
    
  // This is the only callback from the Mail composer to notify the app that the user has carried out certain action
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        switch result {
        case .cancelled:
            print("The user has dismissed the mail composer and deleted the email draft.")
            
        case .saved:
            print("The user has dismissed the mail composer and saved the email draft.")
            
        case .sent:
            // The email request is queued in the user's mail app
            // There is no guarantee that the email is actually sent out!!!
            print("The user has \"sent\" the email out.")
            
        case .failed:
            print("The user cannot send out the email")
            print("Error of sending out the email: \(error.debugDescription)")
            
        }
        controller.dismiss(animated: true)
    }
}

result次のようなユーザーのアクションを表示するプロパティもあります。

  1. cancelled— ユーザーが [キャンセル] ボタンをクリックして、メールの下書きを削除した
  2. saved— ユーザーが [キャンセル] ボタンをクリックして、電子メールの下書きを保存した
  3. sent— ユーザーがメールを*送信*しました
  4. fail— メールアプリへのメールのキューイングでエラーが発生しました

トリック — `sent` の結果が返されたときに、メールは本当に送信されますか?

機内モードなど、ネットワーク接続がないときにメールを送信しようとしましたか? いやいや!_ のdidFinishWithコールバックはMFMailComposeViewControllerDelegate実際に結果を返しますsent!!!

どういう意味ですか?

以下のAppleのドキュメントによるとMFMailComposeViewController、システムメールプログラムにリクエストを送信して、メールを送信する代わりにキューに入れるだけです!!!

Apple 公式ドキュメント— mailComposeController(_:didFinishWith:error:):

ユーザーがこのインターフェイスによって作成された電子メールを送信することを選択した場合、その電子メールは、このメソッドが呼び出されるまでにユーザーのメール プログラムでキューに入れられる必要があります。電子メール メッセージのキューイング中にエラーが発生した場合、errorパラメーターには、発生したエラーの種類を示すエラー オブジェクトが含まれます。

つまり、アプリは、メールが受信者に正常に送信されたかどうかを知ることはできません。

高度な機能 - 電子メールへの添付ファイルの追加

添付ファイルの送信は、ほとんどのユース ケースではまれな機能です。ただし、MFMailComposeViewController作成した電子メールに任意のファイル形式の添付ファイルのリストを添付できます。

// Attach an image to the composed email
let attachmentImageData = UIImage(named: "example_image_name")!.pngData()!
mfMailComposeViewController.addAttachmentData(attachmentImageData, mimeType: "image/png", fileName: "example_file_name")

もっと詳しく知る

メールを送信する方法は他にもたくさんあります。Firebase Extension Trigger Email は使いやすいツールを提供し、開発者が特定の定義済みフィールドを含む Firestore ドキュメントを作成してメールを送信できるようにします。以下は、Trigger Email Extension に関する私の別のブログです。詳しく知りたい方はぜひ読んでみてください。

Firebase 拡張機能 — トリガー メール

結論

Apple は、使いやすいMessageUIフレームワークを提供して、システム メール アプリにジョブを委任することで、アプリがメールを送信できるようにします。アプリは、受信者リスト、件名、メッセージ本文、および添付リストを設定できます。ユーザーが何らかのアクションを実行するMFMailComposeViewControllerDelegateと、結果が返され、アプリはMFMailComposeViewController手動で破棄する必要があります。

からのsent結果は、MFMailComposeViewControllerDelegate実際に電子メールが送信されたことを意味するわけではないことに注意してください。メールリクエストは、システムのメールアプリでのみキューに入れられます!

このブログを楽しんで、良い一日をお過ごしください。