Hi,
Here I’m exploring how to send mails programatically in Swift. Apple has provided MessageUI framework to implement mail functionality in your app. This framework has MFMailComposeViewController class which provides an interface to send/manage emails. We can use this controller to display a user interface within our app.
Let’s learn how it works.
1- Create an instance of MFMailComposeViewController.
let mailComposeViewController = MFMailComposeViewController()
2- Now check if your device can send email or not.
MFMailComposeViewController.canSendMail()
This will return true if device can send mail, else false will be returned.. reason of false could be any. It may be because of no mail account setup.
3- Now conform the delegate methods to handle the listeners.
mailComposeViewController.delegate = self
mailComposeViewController.mailComposeDelegate = self
4- Populate all necessary fields. with their values.
Example: Subject, email recipients, body text, and attachments. You can edit all these once controller is present.
mailComposeViewController.setSubject("This is Subject")
mailComposeViewController.setToRecipients(["example@mail.com"])
mailComposeViewController.setMessageBody("This is message body", isHTML: false)
5- Present the mail controller.
self.present(mailComposeViewController, animated: true, completion: nil)
6- Handle the user actions in delegate method.
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?){
switch (result) {
case .saved:
print("Message saved")
case .cancelled:
print("Message cancelled")
case .failed:
print("Message failed")
case .sent:
print("Message sent")
}
self.dismiss(animated: true, completion: nil)
}
Here you can dismiss the controller or do your stuff on any user action.
Code Snippet:
@IBAction func sendEmailButtonTapped(sender: AnyObject) {
let mailComposeViewController = MFMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
mailComposeViewController.delegate = self
mailComposeViewController.mailComposeDelegate = self
mailComposeViewController.setSubject("This is Subject")
mailComposeViewController.setToRecipients(["example@mail.com"])
mailComposeViewController.setMessageBody("This is message body", isHTML: false)
self.present(mailComposeViewController, animated: true, completion: nil)
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?){
switch (result) {
case .saved:
print("Message saved")
case .cancelled:
print("Message cancelled")
case .failed:
print("Message failed")
case .sent:
print("Message sent")
}
self.dismiss(animated: true, completion: nil)
}
Thank you
0 Comment(s)