LoginSignup
0
0

More than 1 year has passed since last update.

【Swift】アプリ内でメールを送信する

Last updated at Posted at 2023-05-04

はじめに

アプリ内で要望・問い合わせメールを送信機能を実装した。
今後、頻繁に使うと思われるので記録。

実装

MessageUI.frameworkをXCodeに導入
②ViewControllerにメールを送信する処理を実装

ViewController.swift
import UIKit
import MessageUI

final class ViewController: UIViewController {
    @IBOutlet private var sendMailButton: UIButton! {
        didSet {
            sendMailButton.addTarget(self, action: #selector(tapSendMailButton), for: .touchUpInside)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension ViewController: MFMailComposeViewControllerDelegate {
    @objc func tapSendMailButton() {
        guard MFMailComposeViewController.canSendMail() else {
            self.showErrorAlert(title: "通信エラー", message: "メールを送信できませんでした")
        }
        
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self
        mail.setToRecipients([String.emailAddress])
        mail.setSubject(String.emailTitle)
        mail.setMessageBody(String.emailBody, isHTML: false)
        present(mail, animated: true, completion: nil)
    }
    
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        switch result {
        case .cancelled:
            print("キャンセル")
        case .saved:
            print("下書き保存")
        case .sent:
            print("送信成功")
        default:
            print("送信失敗")
            // TODO: アラートで送信できなかったことを通知する
        }
        dismiss(animated: true, completion: nil)
    }
}

private extension ViewController {
    func showErrorAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let gotItAction = UIAlertAction(title: String.ok, style: .default)
        
        self.showAlert(alert: alert, actions: [gotItAction])
    }
}

プレビュー

①iOSアプリ内でメールを開いている画面

②メールを送信する場面でMFMailComposeViewController.canSendMail()がfalseだった場合のアラート

終わりに

補足としては、メーラーのデリゲートメソッド、mailComposeControllerにて、「送信失敗」、「送信成功」といった結果に対してユーザーにフィードバックを返した方が親切。

参考リンク

Message UI | Apple Developer Documentation
【Swift】アプリからメーラーを起動する方法
【Swift】アプリ内でメーラーを起動しメール送信するやり方
【Swift】 お問い合わせ機能の実装
iOSアプリ内でメール画面を開く [MFMailComposeViewController]

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0