从 swift 3 发送电子邮件

Sending an email from swift 3

我正在尝试设置一个带有发送电子邮件选项的应用程序。

我有这个代码:

import Foundation
import MessageUI
import UIKit

class emailClass: UIViewController, MFMailComposeViewControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()

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

    func sendEmail() {      
        let composeVC = MFMailComposeViewController()
        composeVC.mailComposeDelegate = self
        // Configure the fields of the interface.
        composeVC.setToRecipients(["address@example.com"])
        composeVC.setSubject("Hello!")
        composeVC.setMessageBody("Hello this is my message body!", isHTML: false)
        // Present the view controller modally.
        self.present(composeVC, animated: true, completion: nil)
    }

    func mailComposeController(controller: MFMailComposeViewController,
                           didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        // Check the result or perform other tasks.
        // Dismiss the mail compose view controller.
        controller.dismiss(animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

所以我收到这条消息:"Mail services are not available"。 现在我已经在 iCloud 中登录了模拟器设备……所以我认为它应该这样做,但事实并非如此。为什么这不起作用?你能告诉我哪里出了问题吗?我该如何前进?

它不适用于模拟器。请在 iPhone 设备上进行测试。可以参考Apple Developer Portal - MFMailComposeViewController

如果应用程序 运行 在真实设备中

,代码似乎不错并且可以正常工作
MFMailComposeViewController.canSendMail() // returns false for simulators.

你不能在模拟器上测试它,你将能够测试基本的东西,比如 UI,Cancel/Send 按钮点击时事情是如何发生的。

要测试,您必须使用设备,设备中的邮件应用程序应配置一些邮件(例如:abc@xyz.com)。

希望对您有所帮助。

您的代码存在问题,

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

自我呈现 ;-)

如果您不知道当前的视图控制器,只需将其显示在 RootViewController 上即可,即

UIApplication.shared.keyWindow?.rootViewController?.present(...

这是我的做法。看起来你很好地遵循了文档,我想我会添加我的变体以防它帮助别人。另外,这是对当前(2017 年 8 月)语法的更新。

符合MFMailComposeViewControllerDelegate协议,检查设备是否可以发送邮件。

import Foundation
import UIKit
import MessageUI

class WelcomeViewController: UIViewController, MFMailComposeViewControllerDelegate {


override func viewDidLoad() {
    super.viewDidLoad()

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

我的应用程序使用 IBAction 来启动邮件撰写。

@IBAction func sendFeedbackButtonTapped(_ sender: Any) {

    let composeVC = MFMailComposeViewController()
    composeVC.mailComposeDelegate = self

    // Configure the fields of the interface.
    composeVC.setToRecipients(["exampleEmail@email.com"])
    composeVC.setSubject("Message Subject")
    composeVC.setMessageBody("Message content.", isHTML: false)

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

}

关于以下 mailComposeController 函数,文档说

The mail compose view controller is not dismissed automatically. When the user taps the buttons to send the email or cancel the interface, the mail compose view controller calls the mailComposeController(_:didFinishWith:error:) method of its delegate. Your implementation of that method must dismiss the view controller explicitly, as shown in Listing 3. You can also use this method to check the result of the operation.

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

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

来源Apple Documentation: MFMailComposeViewController

Swift 5 中发送电子邮件很容易 5 您需要确认并实施 MFMailComposeViewControllerDelegate 并检查我们是否可以在此设备上发送电子邮件

这是我在任务中使用的一小段代码

import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    //MARK: IBAction Method for Button click
    @IBAction func sendEmail(_ sender: Any) {
        //TODO:  You should chack if we can send email or not
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients(["you@yoursite.com"])
            mail.setSubject("Email Subject Here")
            mail.setMessageBody("<p>You're so awesome!</p>", isHTML: true)
            present(mail, animated: true)
        } else {
            print("Application is not able to send an email")
        }
    }

    //MARK: MFMail Compose ViewController Delegate method
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true)
    }
}

PS: Please don't forget you need to test this on real device