how to send a mail from my iOS application- SWIFT
Asked Answered
W

5

14

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()

    }
}
Whiffet answered 25/4, 2016 at 10:37 Comment(0)
C
17

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

Clayclaybank answered 8/3, 2018 at 9:20 Comment(0)
A
13

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

Avelinaaveline answered 25/4, 2016 at 10:42 Comment(5)
do i have to delete the func sndEmail()?Whiffet
@Whiffet just change func sendEmail() { lineAvelinaaveline
sorry for the silly question but when it is like that.. it still doesnt worksWhiffet
@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) }Whiffet
@Whiffet I'm glad to hear, feel free to accept answerAvelinaaveline
W
10

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)
    }
}
Wellgroomed answered 31/3, 2017 at 6:2 Comment(0)
M
7

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)
}
Marrero answered 25/4, 2016 at 13:22 Comment(1)
Thanks for the answer. And how can Mail Services be enabled?Gymnasiast
Y
1

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{

Yancey answered 27/2, 2017 at 22:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.