DEV Community

Trần Thanh Vũ
Trần Thanh Vũ

Posted on • Edited on

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.

    I used a static object to able to reuse it in my project.

    
        class EmailHelper: NSObject {
            /// singleton
            static let shared = EmailHelper()
            private override init() {}
        }
    
    


  2. Able to open the external mail or settings app in case users 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!


Top comments (0)