iOS 개발자 — 이메일 보내기

Nov 26 2022
이메일은 21세기 최고의 커뮤니케이션 채널 중 하나입니다. 몇 초 안에 여러 수신자에게 정보를 전달할 수 있습니다.

이메일은 21세기 최고의 커뮤니케이션 채널 중 하나입니다. 몇 초 안에 여러 수신자에게 정보를 전달할 수 있습니다. 이메일 기능을 앱에 통합하는 것을 생각해 본 적이 있습니까?

Apple은 MessageUI개발자를 위해 사용이 간편한 프레임워크를 제공했습니다. 다음 속성을 구성할 수 있습니다.

  1. 수신자 목록
  2. 주제
  3. 메시지 본문
  4. 첨부파일

단계별 절차

1단계) 기기에서 이메일을 보낼 수 있는지 확인

import MessageUI

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

1. 앱 사용자가 시스템 메일링 앱에서 아직 이메일 계정을 설정하지 않았습니다.

2. 이 StackOverflow 답변을 참조하여 iOS MDM 프로필에서 메일링 기능을 비활성화했습니다.

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— 메일 앱에 이메일을 대기시키는 데 오류가 있습니다.

Trick — '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 Extension — 트리거 이메일

결론

MessageUIApple은 작업을 시스템 메일링 앱에 위임하여 앱이 이메일을 보낼 수 있도록 사용하기 쉬운 프레임워크를 제공합니다. 앱은 수신자 목록, 제목, 메시지 본문 및 첨부 파일 목록을 설정할 수 있습니다. 사용자가 조치를 취하면 MFMailComposeViewControllerDelegate에서 결과를 다시 실행하고 앱에서 MFMailComposeViewController수동으로 해제해야 합니다.

sent의 결과 가 실제로 이메일이 전송 되었음을 MFMailComposeViewControllerDelegate의미하지는 않습니다. 이메일 요청은 시스템 메일링 앱에서만 대기합니다!

이 블로그를 즐기시고 좋은 하루 보내시기 바랍니다!