Iphone email code

Here is an example of how to send an email using the iPhone's built-in Mail app using Swift:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a new email
        let mailComposeViewController = configureMailComposeViewController()

        // Present the view controller
        if MFMailComposeViewController.canSendMail() {
            self.present(mailComposeViewController, animated: true, completion: nil)
        } else {
            print("Mail services are not available")
        }
    }

    // Create a new email
    func configureMailComposeViewController() -> MFMailComposeViewController {
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self

        // Set the subject and body of the email
        mail.setSubject("Test Email")
        mail.setMessageBody("This is a test email", isHTML: false)

        // Add recipients
        mail.setToRecipients(["[email protected]"])

        return mail
    }
}

// Implement the MFMailComposeViewControllerDelegate protocol
extension ViewController: MFMailComposeViewControllerDelegate {
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        // Dismiss the mail compose view controller
        controller.dismiss(animated: true, completion: nil)
    }
}

This code creates a new email with a subject and body, sets the recipient, and presents the email compose view controller. The MFMailComposeViewControllerDelegate protocol is implemented to handle the result of the email composition.

You can also add attachments to the email by using the addAttachmentData method:

mail.addAttachmentData(attachmentData, mimeType: "image/jpeg", fileName: "image.jpg")

And you can also set the CC and BCC recipients by using the setCCRecipients and setBCCRecipients methods:

mail.setCCRecipients([["[email protected]"]])
mail.setBCCRecipients([["[email protected]"]])

Please note that the MFMailComposeViewController is only available on iOS devices, and it's not available on macOS or watchOS.