Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send a mail from my iOS application- SWIFT

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

    }
}
like image 659
jonathan Avatar asked Apr 25 '16 10:04

jonathan


People also ask

Can I send an email on my Iphone?

In the Mail app , you can write and edit email from any of your email accounts.


1 Answers

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

like image 88
Mr.Javed Multani Avatar answered Oct 14 '22 15:10

Mr.Javed Multani