我在Swift 2中使用MailCore2时出错

时间:2016-05-02 12:13:23

标签: ios swift mailcore2

我在我的iOS应用程序中使用Swift中的MailCore2在后台发送消息到电子邮件而没有打开内置邮件应用程序,但是当我在我的设备(真实设备)上运行应用程序时,我遇到了这个问题:

我的完整发送按钮代码:

@IBAction func sendButton(sender: AnyObject) {

    var smtpSession = MCOSMTPSession()
    smtpSession.hostname = "smtp.gmail.com"
    smtpSession.username = "from-email"
    smtpSession.password = "password"
    smtpSession.port = 465
    smtpSession.authType = MCOAuthType.SASLPlain
    smtpSession.connectionType = MCOConnectionType.TLS
    smtpSession.connectionLogger = {(connectionID, type, data) in
        if data != nil {
            if let string = NSString(data: data, encoding: NSUTF8StringEncoding){
                NSLog("Connectionlogger: \(string)")
            }
        }
    }

    var builder = MCOMessageBuilder()
    builder.header.to = [MCOAddress(displayName: "AAA", mailbox: "to-email")]
    builder.header.from = MCOAddress(displayName: "RRR", mailbox: "from-email")
    builder.header.subject = messageTitleTextField.text
    var message = messageTextView.text
    builder.htmlBody = message

    let rfc822Data = builder.data()
    let sendOperation = smtpSession.sendOperationWithData(rfc822Data)
    sendOperation.start { (error) -> Void in
        if (error != nil) {
            NSLog("Error sending email: \(error)")
        } else {
            NSLog("Sent successfully, Thanks!")
        }
    }
}

错误:

 Optional(Error Domain=MCOErrorDomain Code=5 "Unable to authenticate with the current session's credentials." UserInfo={NSLocalizedDescription=Unable to authenticate with the current session's credentials.})

2 个答案:

答案 0 :(得分:2)

我已经从gmail帐户更改了不安全应用的设置但我通过从此链接解锁gmail帐户解决了凭据问题 https://accounts.google.com/DisplayUnlockCaptcha

答案 1 :(得分:-2)

就我而言,我必须“更改安全性较低的应用程序的帐户访问权限”

https://support.google.com/accounts/answer/6010255?hl=en

如果有人遇到这个问题,知道它实际上是谷歌方面的安全问题,那将非常有帮助,因此必须予以解决...我将其保留,因为当这件事发生在我身上时,错误什么也没说我不得不搜索问题,以找出您必须转到google上的链接,并了解如何正确设置它,这很浪费时间,这对于希望通过smtp和Google帐户发送邮件的其他人会有所帮助