Photo by Solen Feyissa on Unsplash

How to send emails in swiftUI

Opening an email in an iOS application is a common feature, and I think most applications have it. But sometimes developers’ complex mind makes its implementation more complex than it is.

In the case of swiftUI, the implementation doesn’t change, you can use the old code to implement it. In my project, it works perfectly. You can find the full version of the code below.

Here are some requirements implemented in that file.

  1. Create and use an object to help you checking the status of the mail service and handling the MailCompose’s delegate.
class EmailHelper: NSObject {    /// singleton    static let shared = EmailHelper()    private override init() {}}

2. Able to open the external mail or settings app in case use didn’t set up any email.

I just supported the external mails app such as Gmail, Mail. So, if you want to add more, please do it yourself. Note, you have to add Schemes of the app which you want to support.

/// Remember to add the below code to Info.plist
/// <key>LSApplicationQueriesSchemes</key>
/// <array>
/// <string>googlegmail</string>
/// </array>

3. Related to swiftUI, you don’t have to use UIViewRepresentable or UIViewControllerRepresentable here, because you just want to open the mail but don’t want to embed it in a View

struct SettingsView: View {
var body: some View {
return Form {
Section(header: Text(“SUPPORT”)) {
Button(“Help”) {
EmailHelper.shared
.send(subject: “Help”,
body: “”,
to: [GlobalConstant.App.contactEmail])
}
}
}
}
}

Happy coding!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store