Use the Messageui.framework framework in addition to sending text messages, you can also send email, the steps are as follows:
(1) First determine if the device has a Send mail function (2) If the device allows sending mail, create a Mfmailcomposeviewcontroller view controller, and set the message header, body content, recipients, attachments, and so on. (3) After the message is sent, the callback agent method is executed, which can get the sending result (success, failure or cancellation)as follows:
The code is as follows:
import UIKit
import MessageUI
class ViewController: UIViewController, UINavigationControllerDelegate,
MFMailComposeViewControllerDelegate {
override func viewDidLoad () {
super.viewDidLoad ()
// First, determine whether the device has the function of sending emails
if MFMailComposeViewController.canSendMail () {
let controller = MFMailComposeViewController ()
// Set proxy
controller.mailComposeDelegate = self
// Set theme
controller.setSubject ("I am the subject of the message")
// Set the recipient
controller.setToRecipients (["a1@hangge.com", "a2@hangge.com"])
// Set the CC
controller.setCcRecipients (["b1@hangge.com", "b2@hangge.com"])
// Set Bcc
controller.setBccRecipients (["c1@hangge.com", "c2@hangge.com"])
// Add image attachment
let path = Bundle.main.path (forResource: "hangge.png", ofType: "")
let url = URL (fileURLWithPath: path!)
let myData = try! Data (contentsOf: url)
controller.addAttachmentData (myData, mimeType: "image / png",
fileName: "swift.png")
// Set email body content (supports html)
controller.setMessageBody ("I am the message body", isHTML: false)
// Open the interface
self.present (controller, animated: true, completion: nil)
} else {
print ("This device cannot send mail")
}
}
// Send mail proxy method
func mailComposeController (_ controller: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss (animated: true, completion: nil)
switch result {
case .sent:
print ("Mail Sent")
case .cancelled:
print ("Mail cancelled")
case .saved:
print ("Mail saved")
case .failed:
print ("Failed to send mail")
}
}
override func didReceiveMemoryWarning () {
super.didReceiveMemoryWarning ()
}
}
Swift-The implementation of the mail sending function