how to send a mail from my iOS application- SWIFT

jonathan  picture jonathan · Apr 25, 2016 · Viewed 25.9k times · Source

I want to send a mail from my application. I am doing my first steps with SWIFT and i have stuck at a point. I want to press a button and open up the mail. Can you please tell me how to do the button connection? I think it should be an action but I don't know where to put it on the code

import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    func sendEmail() {
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients([])
        mailVC.setSubject("Subject for email")
        mailVC.setMessageBody("Email message string", isHTML: false)

        presentViewController(mailVC, animated: true, completion: nil)
    }

    // MARK: - Email Delegate 

    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        controller.dismissViewControllerAnimated(true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}

Answer

Mr.Javed Multani picture Mr.Javed Multani · Mar 8, 2018

Import library first:

import MessageUI

set delegate like:

MFMailComposeViewControllerDelegate

Write pretty code:

 @IBAction func buttonHandlerSendEmail(_ sender: Any) {

  let mailComposeViewController = configureMailComposer()
    if MFMailComposeViewController.canSendMail(){
        self.present(mailComposeViewController, animated: true, completion: nil)
    }else{
        print("Can't send email")
    }
}
func configureMailComposer() -> MFMailComposeViewController{
    let mailComposeVC = MFMailComposeViewController()
    mailComposeVC.mailComposeDelegate = self
    mailComposeVC.setToRecipients([self.textFieldTo.text!])
    mailComposeVC.setSubject(self.textFieldSubject.text!)
    mailComposeVC.setMessageBody(self.textViewBody.text!, isHTML: false)
    return mailComposeVC
}

Also write delegate method like:

//MARK: - MFMail compose method
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    controller.dismiss(animated: true, completion: nil)
}

enter image description here

100% working and tested