ios - 如何从我的 iOS 应用程序发送邮件 - SWIFT

标签 ios xcode swift email mfmailcomposeviewcontroller

我想从我的应用程序发送邮件。我正在 SWIFT 迈出第一步,但我一直卡在某个点上。我想按下一个按钮并打开邮件。你能告诉我如何进行按钮连接吗?我认为这应该是一个 Action ,但我不知道把它放在代码的什么地方

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

    }
}

最佳答案

首先导入库:

import MessageUI

像这样设置委托(delegate):

MFMailComposeViewControllerDelegate

编写漂亮的代码:

 @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
}

也可以这样写委托(delegate)方法:

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

enter image description here

100% 工作并经过测试

关于ios - 如何从我的 iOS 应用程序发送邮件 - SWIFT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36838166/

相关文章:

ios - 每次运行应用程序时,我都必须下载新数据

objective-c - 从 XCode 项目连接到 Oracle 数据库

ios - 安装在音频引擎上的 Tap 仅生成短文件

ios - 问题注意 Swift 方法作为 Objective C 中的选择器并在 Swift ios App 中使用 Objective C 对象

arrays - UITableViewCell 如何知道要从数组或字典加载什么 JSON

ios - 为什么我的 CLLocationManager 没有响应 startMonitoringForRegion?

ios - 无法在真实设备上运行 RealTimeRoom Google-Play-Games iOS ButtonClicker2000 示例

iphone - 滑入式工具栏

ios - 如何以编程方式更改 UIDatePicker 的选定日期颜色 - Swift 4?

ios - 参与者QuitInTurnWithOutcome :nextParticipants:turnTimeout:matchData:completionHandler: in Swift - xcode compile error