SwiftUI — Send email using MFMailCompose from MessageUI

Alex Protyagov
2 min readJun 6, 2022

In the previous article, SwiftUI Send Email, we looked at the simplest way to send email from SwiftUI app using URL. However, sometimes you might need more control over emails. For that, we can import MessageUI and use MFMailComposeViewController to compose and send emails. The difficulty of this approach is that SwiftUI does not support it directly and we have to wrap all work inside of UIView representable.

First, we are going to design MailView that wraps MFMail components. This view can be initialized with a list of email recipients, subject and body.

Next, we can invoke this view from our view that has the “Send Email” button. This part is a bit more involved than I would like it to be. We need to create 2 variables, one for triggering email composing, and second is for results.

Next, we can invoke this view from our view that has the “Send Email” button. This part is a bit more involved. We need to create 2 variables, one for triggering email composing, and second is for results.
We also need to make sure device is capable of sending email, otherwize clicking send button would crush application. To prevent it we disable button if device cannot send email (for example, email app is delete by user)

Thank you for reading this article.

--

--

Alex Protyagov

Tech enthusiast with 15 years of experience creating solutions for small startups, large scale retail, media, and government entities.