skip to Main Content

After a user in my app registers, they are taken to a static screen until they verify their email. This screen contains a button that when pressed, is supposed to open the IOS mail app. How do I do this in SwiftUI?

I’m aware that I can send an email with UIApplication.shared.open(URL(string: "mailto:...")) but I’m trying to specifically just open the app. I’ve tried googling but all the tutorials I’ve seen are for sending emails.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to @CloudBalancing for finding the link. The url to open the mail app is URL(string: "message://").

    func openMail() {
        let url = URL(string: "message://")
        if let url = url {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    

  2. func openMail(emailTo:String, subject: String, body: String) {
        if let url = URL(string: "mailto:(emailTo)?subject=(subject.fixToBrowserString())&body=(body.fixToBrowserString())"),
           UIApplication.shared.canOpenURL(url)
        {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
    
    extension String {
        func fixToBrowserString() -> String {
            self.replacingOccurrences(of: ";", with: "%3B")
                .replacingOccurrences(of: "n", with: "%0D%0A")
                .replacingOccurrences(of: " ", with: "+")
                .replacingOccurrences(of: "!", with: "%21")
                .replacingOccurrences(of: """, with: "%22")
                .replacingOccurrences(of: "\", with: "%5C")
                .replacingOccurrences(of: "/", with: "%2F")
                .replacingOccurrences(of: "‘", with: "%91")
                .replacingOccurrences(of: ",", with: "%2C")
                //more symbols fixes here: https://mykindred.com/htmlspecialchars.php
        }
    }
    

    if you have some issues with opening of the email link – probably you need to add addidtional fixes to function fixToBrowserString()

    usage in SwiftUI:

    Button("Support Email") { 
        openMail(emailTo: "[email protected]", 
                 subject: "App feedback", 
                 body: "Huston, we have a problem!nn...")
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search