Sending Mail from an iPhone App with Monotouch

You can send email on the iPhone from within your application using the MFMailComposeViewController in the MonoTouch.MessageUI namespace. Simply check if the device is able to send mail using the CanSendMail property and if it is true, bring up an MFMailComposeViewController. The controller has properties to add attachments (using the AddAttachmentData method), set the message body, send html mail, add cc recipients, etc. After hydrating your controller and presenting it, you can listen for completion results by subscribing to the Finished event (or you could do it the Delegate way and override the Finished virtual function on MFMailComposeViewControllerDelegate as well). In the callback you get back a result object, an error object and the controller itself via the MFComposeResultEventArgs, which you can use to present the completion status and dismiss the controller. Here’s a simple example:

        MFMailComposeViewController _mail;
        ...

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();
            
            mailButton.TouchUpInside += (o, e) =>
            {
                if (MFMailComposeViewController.CanSendMail) {
                    _mail = new MFMailComposeViewController ();
                    _mail.SetMessageBody ("This is the body of the email", 
                        false);
                    _mail.Finished += HandleMailFinished;
                    
                    this.PresentModalViewController (_mail, true);
                    
                } else {
                    // handle not being able to send mail
                }
            };
        }

        void HandleMailFinished (object sender, MFComposeResultEventArgs e)
        {
            if (e.Result == MFMailComposeResult.Sent) {
                UIAlertView alert = new UIAlertView ("Mail Alert", "Mail Sent",
                    null, "Yippie", null);
                alert.Show ();
                
                // you should handle other values that could be returned 
                // in e.Result and also in e.Error 
            }
            e.Controller.DismissModalViewControllerAnimated (true);
        }

Update: Added link to the sample project here.

About these ads

8 thoughts on “Sending Mail from an iPhone App with Monotouch

  1. Pingback: MonoTouch.Info
  2. Hey Mike,

    did you successfully handle the Cancel action? E.g. when dismissing the draft. It does not jump into the Finished handler for me…
    Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s