iOS Developer Library

Developer

Message UI Framework Reference MFMailComposeViewController Class Reference

Options
Deployment Target:

On This Page
Language:

MFMailComposeViewController

The MFMailComposeViewController class provides a standard interface for managing, editing, and sending an email message. Use this view controller to display a standard email interface inside your app. Before presenting the interface, populate the fields with initial values for the subject, email recipients, body text, and attachments of the email. After presenting the interface, the user can edit your initial values before sending the email.

The composition interface does not guarantee the delivery of your email message; it only lets you construct the initial message and present it for user approval. The user may opt to cancel the composition interface, in which case the message and its contents are discarded. If the user opts to send the message, the message is queued in the user’s Mail app outbox. The Mail app is ultimately responsible for sending the message.

Figure 1The mail composition interface image: ../Art/mail_composition_2x.png

An alternate way to compose emails is to create and open a URL that uses the mailto scheme. URLs of that type are directed to the built-in Mail app, which uses your URL to configure a message. For information about the structure of mailto URLs, see Apple URL Scheme Reference.

Checking the Availability of the Composition Interface

Before presenting the mail compose view controller, always call the the canSendMail method to see if the current device is configured to send email. If the user’s device is not set up for the delivery of email, you can notify the user or simply disable the email dispatch features in your application. You should not attempt to use this interface if the canSendMail method returns NOfalse.

Listing 1Checking the availability of mail services

Objective-C

  1. if (![MFMailComposeViewController canSendMail]) {
  2. NSLog(@"Mail services are not available.");
  3. return;
  4. }

Swift

  1. if !MFMailComposeViewController.canSendMail() {
  2. print("Mail services are not available")
  3. return
  4. }

Configuring and Displaying the Composition Interface

After verifying that mail services are available, you can create and configure the mail composition view controller and then present it like you would any other view controller. Use the methods of this class to specify the subject, recipients, and message body of the email, including any attachments you want to send with the message. Listing 2 shows how to configure the composition interface and present it modally. Always assign a delegate to the mailComposeDelegate property. The delegate is responsible for dismissing the composition interface later.

Listing 2Configuring and presenting the composition interface

Objective-C

  1. MFMailComposeViewController* composeVC = [[MFMailComposeViewController alloc] init];
  2. composeVC.mailComposeDelegate = self;
  3. // Configure the fields of the interface.
  4. [composeVC setToRecipients:@[@"address@example.com"]];
  5. [composeVC setSubject:@"Hello!"];
  6. [composeVC setMessageBody:@"Hello from California!" isHTML:NO];
  7. // Present the view controller modally.
  8. [self presentViewController:composeVC animated:YES completion:nil];

Swift

  1. let composeVC = MFMailComposeViewController()
  2. composeVC.mailComposeDelegate = self
  3. // Configure the fields of the interface.
  4. composeVC.setToRecipients(["address@example.com"])
  5. composeVC.setSubject("Hello!")
  6. composeVC.setMessageBody("Hello from California!", isHTML: false)
  7. // Present the view controller modally.
  8. self.presentViewController(composeVC, animated: true, completion: nil)

The mail compose view controller is not dismissed automatically. When the user taps the buttons to send the email or cancel the interface, the mail compose view controller calls the mailComposeController:didFinishWithResult:error: method of its delegate. Your implementation of that method must dismiss the view controller explicitly, as shown in Listing 3. You can also use this method to check the result of the operation.

Listing 3Dismissing the mail compose view controller

Objective-C

  1. - (void)mailComposeController:(MFMailComposeViewController *)controller
  2. didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
  3. // Check the result or perform other tasks.
  4. // Dismiss the mail compose view controller.
  5. [self dismissViewControllerAnimated:YES completion:nil];
  6. }

Swift

  1. func mailComposeController(controller: MFMailComposeViewController,
  2. didFinishWithResult result: MFMailComposeResult, error: NSError?) {
  3. // Check the result or perform other tasks.
  4. // Dismiss the mail compose view controller.
  5. controller.dismissViewControllerAnimated(true, completion: nil)
  6. }

The user can delete a queued message before it is sent. Although the view controller reports the success or failure of the operation to its delegate, this class does not provide a way for you to verify whether the email was actually sent.

For more information on how to present and dismiss view controllers, see View Controller Programming Guide for iOS.

  • Returns a Boolean indicating whether the current device is able to send email.

    Declaration

    Swift

    class func canSendMail() -> Bool

    Objective-C

    + (BOOL)canSendMail

    Return Value

    YEStrue if the device is configured for sending email or NOfalse if it is not.

    Discussion

    You should call this method before attempting to display the mail composition interface. If it returns NOfalse, you must not display the mail composition interface.

    Availability

    Available in iOS 3.0 and later.

  • Sets the initial text for the subject line of the email.

    Declaration

    Swift

    func setSubject(_ subject: String)

    Objective-C

    - (void)setSubject:(NSString *)subject

    Parameters

    subject

    The text to display in the subject line.

    Discussion

    This method replaces the previous subject text with the new text. Call this method before you display the mail composition interface only. Do not call it after presenting the interface to the user.

    Availability

    Available in iOS 3.0 and later.

  • Sets the initial recipients to include in the email’s “To” field.

    Declaration

    Swift

    func setToRecipients(_ toRecipients: [String]?)

    Objective-C

    - (void)setToRecipients:(NSArray<NSString *> *)toRecipients

    Parameters

    toRecipients

    An array of NSString objects, each of which contains the email address of a single recipient.

    Discussion

    This method replaces the previous recipients with the new ones listed in the toRecipients parameter. This method does not filter out duplicate email addresses, so if duplicates are present, multiple copies of the email message may be sent to the same address.

    Call this method before you display the mail composition interface only. Do not call it after presenting the interface to the user.

    Availability

    Available in iOS 3.0 and later.

  • Sets the initial recipients to include in the email’s “Cc” field.

    Declaration

    Swift

    func setCcRecipients(_ ccRecipients: [String]?)

    Objective-C

    - (void)setCcRecipients:(NSArray<NSString *> *)ccRecipients

    Parameters

    ccRecipients

    An array of NSString objects, each of which contains the email address of a single recipient.

    Discussion

    This method replaces the previous carbon-copy recipients with the new ones listed in the ccRecipients parameter. This method does not filter out duplicate email addresses, so if duplicates are present, multiple copies of the email message may be sent to the same address.

    Call this method before you display the mail composition interface only. Do not call it after presenting the interface to the user.

    Availability

    Available in iOS 3.0 and later.

  • Sets the initial recipients to include in the email’s “Bcc” field.

    Declaration

    Swift

    func setBccRecipients(_ bccRecipients: [String]?)

    Objective-C

    - (void)setBccRecipients:(NSArray<NSString *> *)bccRecipients

    Parameters

    bccRecipients

    An array of NSString objects, each of which contains the email address of a single recipient.

    Discussion

    This method replaces the previous blind carbon-copy recipients with the new ones listed in the bccRecipients parameter. This method does not filter out duplicate email addresses, so if duplicates are present, multiple copies of the email message may be sent to the same address.

    Call this method before you display the mail composition interface only. Do not call it after presenting the interface to the user.

    Availability

    Available in iOS 3.0 and later.

  • Sets the initial body text to include in the email.

    Declaration

    Swift

    func setMessageBody(_ body: String, isHTML isHTML: Bool)

    Objective-C

    - (void)setMessageBody:(NSString *)body isHTML:(BOOL)isHTML

    Parameters

    body

    The initial body text of the message. The text is interpreted as either plain text or HTML depending on the value of the isHTML parameter.

    isHTML

    Specify YEStrue if the body parameter contains HTML content or specify NOfalse if it contains plain text.

    Discussion

    This method replaces the previous body content with the new content. If the user has a signature file, the body content is inserted immediately before the signature. If you want to include images with your content, you must attach the images separately using the addAttachmentData:mimeType:fileName: method.

    Call this method before you display the mail composition interface only. Do not call it after presenting the interface to the user.

    Availability

    Available in iOS 3.0 and later.

  • Adds the specified data as an attachment to the message.

    Declaration

    Swift

    func addAttachmentData(_ attachment: NSData, mimeType mimeType: String, fileName filename: String)

    Objective-C

    - (void)addAttachmentData:(NSData *)attachment mimeType:(NSString *)mimeType fileName:(NSString *)filename

    Parameters

    attachment

    The data to attach. Typically, this is the contents of a file that you want to include. This parameter must not be nil.

    mimeType

    The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be nil.

    filename

    The preferred filename to associate with the data. This is the default name applied to the file when it is transferred to its destination. Any path separator (/) characters in the filename are converted to underscore (_) characters prior to transmission. This parameter must not be nil.

    Discussion

    This method attaches the specified data after the message body but before the user’s signature. You may attach multiple files (using different file names) but must do so prior to displaying the mail composition interface. Do not call this method after presenting the interface to the user.

    Availability

    Available in iOS 3.0 and later.

  • Result codes returned when the mail composition interface is dismissed.

    Declaration

    Swift

    struct MFMailComposeResult : RawRepresentable, Equatable { init(_ rawValue: UInt32) init(rawValue rawValue: UInt32) var rawValue: UInt32 }

    Objective-C

    enum MFMailComposeResult { MFMailComposeResultCancelled, MFMailComposeResultSaved, MFMailComposeResultSent, MFMailComposeResultFailed }; typedef enum MFMailComposeResult MFMailComposeResult;

    Constants

    • MFMailComposeResultCancelled

      MFMailComposeResultCancelled

      The user cancelled the operation. No email message was queued.

      Available in iOS 3.0 and later.

    • MFMailComposeResultSaved

      MFMailComposeResultSaved

      The email message was saved in the user’s Drafts folder.

      Available in iOS 3.0 and later.

    • MFMailComposeResultSent

      MFMailComposeResultSent

      The email message was queued in the user’s outbox. It is ready to send the next time the user connects to email.

      Available in iOS 3.0 and later.

    • MFMailComposeResultFailed

      MFMailComposeResultFailed

      The email message was not saved or queued, possibly due to an error.

      Available in iOS 3.0 and later.

    Import Statement

    Objective-C

    @import MessageUI;

    Swift

    import MessageUI

    Availability

    Available in iOS 3.0 and later.

  • The domain used for NSError objects associated with the mail composition interface.

    Declaration

    Swift

    let MFMailComposeErrorDomain: String

    Objective-C

    NSString *const MFMailComposeErrorDomain;

    Constants

    • MFMailComposeErrorDomain

      MFMailComposeErrorDomain

      The error domain associated with NSError objects.

      Available in iOS 3.0 and later.

  • Error codes for NSError objects associated with the mail composition interface.

    Declaration

    Swift

    struct MFMailComposeErrorCode : RawRepresentable, Equatable { init(_ rawValue: UInt32) init(rawValue rawValue: UInt32) var rawValue: UInt32 }

    Objective-C

    enum MFMailComposeErrorCode { MFMailComposeErrorCodeSaveFailed, MFMailComposeErrorCodeSendFailed }; typedef enum MFMailComposeErrorCode MFMailComposeErrorCode;

    Constants

    • MFMailComposeErrorCodeSaveFailed

      MFMailComposeErrorCodeSaveFailed

      An error occurred trying to save the email message to the Drafts folder.

      Available in iOS 3.0 and later.

    • MFMailComposeErrorCodeSendFailed

      MFMailComposeErrorCodeSendFailed

      An error occurred while trying to queue or send the email message.

      Available in iOS 3.0 and later.

    Import Statement

    Objective-C

    @import MessageUI;

    Swift

    import MessageUI

    Availability

    Available in iOS 3.0 and later.