how to send a mail from my iOS application- SWIFT

27,820

Solution 1

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

Solution 2

change sendEmail like this:

@IBAction func sendEmail(sender: AnyObject) {
    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)
}

and connect in Interface builder your button to this action

Solution 3

Swift 3

let composer = MFMailComposeViewController()

if MFMailComposeViewController.canSendMail() {
     composer.mailComposeDelegate = self
     composer.setToRecipients(["Email1", "Email2"])
     composer.setSubject("Test Mail")
     composer.setMessageBody("Text Body", isHTML: false)
     present(composer, animated: true, completion: nil)
}

Delegate method

class SendMailViewController: MFMailComposeViewControllerDelegate {
   func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        dismiss(animated: true, completion: nil)
    }
}

Solution 4

To send mail, generally MFMailComposer is used. It can be tested on device as it doesn't work on iOS simulator.

For testing whether mail service is available or not, use below function,

if !MFMailComposeViewController.canSendMail() {
    print("Mail services are not available")
    return
}

and to send mail, use below code in your function or action of button.

let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self

// Configure the fields of the interface.
composeVC.setToRecipients(["[email protected]"])
composeVC.setSubject("Hello World!")
composeVC.setMessageBody("Hello from iOS!", isHTML: false)

// Present the view controller modally.
self.presentViewController(composeVC, animated: true, completion: nil)

There is delegate method on completion of sending mail which can be defined as below shown,

func mailComposeController(controller: MFMailComposeViewController,
                           didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    // Check the result or perform other tasks.

    // Dismiss the mail compose view controller.
    controller.dismissViewControllerAnimated(true, completion: nil)
}

Solution 5

to Anton Platonov add: import MessageUI at the begging of your source file, and when you declaring class for your view controller add protocol: class FirstVC: UIViewController, MFMailComposeViewControllerDelegate{

Share:
27,820
jonathan
Author by

jonathan

Updated on March 08, 2020

Comments

  • jonathan
    jonathan about 4 years

    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()
    
        }
    }
    
  • jonathan
    jonathan about 8 years
    do i have to delete the func sndEmail()?
  • gvuksic
    gvuksic about 8 years
    @jonathan just change func sendEmail() { line
  • jonathan
    jonathan about 8 years
    sorry for the silly question but when it is like that.. it still doesnt works
  • jonathan
    jonathan about 8 years
    @IBAction func email(sender: AnyObject) { //func email() { 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) }
  • gvuksic
    gvuksic about 8 years
    @jonathan I'm glad to hear, feel free to accept answer
  • Anton Platonov
    Anton Platonov about 7 years
    Thanks for the answer. And how can Mail Services be enabled?