“请设置邮件帐户以便发送电子邮件”Swift出错

时间:2017-02-16 14:27:54

标签: ios iphone swift email email-integration

我尝试通过我的应用发送电子邮件,但我收到了一个名为

的错误
  

“请设置邮件帐户以发送电子邮件”。

我的代码块在下面。

import MessageUI

@IBAction func emailTapped(_ sender: Any) {   

    let mailComposerVC = MFMailComposeViewController()
    mailComposerVC.mailComposeDelegate = self
    mailComposerVC.setToRecipients(["abc@gmail.com"])
    mailComposerVC.setSubject("Sending you an in-app e-mail...")
    mailComposerVC.setMessageBody("Sending e-mail in-app is not so bad!", isHTML: false)

    if MFMailComposeViewController.canSendMail() {
        self.present(mailComposerVC, animated: true, completion: {() -> Void in })
    }  
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Swift.Error?){
    controller.dismiss(animated: true) { () -> Void in } 
}

1 个答案:

答案 0 :(得分:5)

代码看起来不错(虽然可以改进),您需要在正在使用的设备上设置电子邮件帐户。

import MessageUI
    @IBAction func emailTapped(_ sender: Any) {  

            if MFMailComposeViewController.canSendMail() { 
                let mailComposerVC = MFMailComposeViewController()
                mailComposerVC.mailComposeDelegate = self
                mailComposerVC.setToRecipients(["abc@gmail.com"])
                mailComposerVC.setSubject("Sending you an in-app e-mail...")
                mailComposerVC.setMessageBody("Sending e-mail in-app is not so bad!", isHTML: false)

                self.present(mailComposerVC, animated: true, completion: {() -> Void in })
            }

        }

        func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Swift.Error?){
            controller.dismiss(animated: true) { () -> Void in }

        }

现在,在iPhone上搜索Settings应用,然后转到Mail - > Accounts - > Add Account在手机上设置电子邮件帐户。 您可以查看此video