使用Swift发送电子邮件

42

如何在应用程序中使用Swift发送电子邮件。例如,您的用户想要在Parse(或非Parse)社交媒体应用程序中重置其密码,但您不想使用MessageUI,因为您希望它是自动的。我已经进行了一些研究,发现可以通过mailgun实现,但我无法弄清楚如何在Swift和XCode 6中使用它。你能帮我吗?


你尝试过什么? - Loko
2个回答

88

当然可以。

import Foundation
import UIKit
import MessageUI

class ViewController: ViewController,MFMailComposeViewControllerDelegate {

    @IBAction func sendEmailButtonTapped(sender: AnyObject) {
        let mailComposeViewController = configuredMailComposeViewController()
        if MFMailComposeViewController.canSendMail() {
            self.presentViewController(mailComposeViewController, animated: true, completion: nil)
        } else {
            self.showSendMailErrorAlert()
        }
    }

    func configuredMailComposeViewController() -> MFMailComposeViewController {
        let mailComposerVC = MFMailComposeViewController()
        mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property

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

        return mailComposerVC
    }

    func showSendMailErrorAlert() {
        let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail.  Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
        sendMailErrorAlert.show()
    }

    // MARK: MFMailComposeViewControllerDelegate

    func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
        controller.dismissViewControllerAnimated(true, completion: nil)

    }
}

参考文献 Andrew Bancroft的博客文章


12
你不想使用MessageUI,因为你希望它是自动的。 - Matthias Bauch
当使用IOS9.2模拟器时,视图会崩溃并显示“viewServiceDidTerminateWithError”消息。然而,其他问题说明这只是模拟器的问题,解决方案将在真实设备上运行。 - Dashrath
7
非常熟悉。https://www.andrewcbancroft.com/2014/08/25/send-email-in-app-using-mfmailcomposeviewcontroller-with-swift/ - n13

7

Parse支持Mailgun和Mandrill两种邮件服务,并提供了开箱即用的支持。 请参考它们的文档

您需要编写一个CloudCode函数,并从应用程序中调用它。

PFCloud.callFunctionInBackground("hello", withParameters:[:]) {
  (result: AnyObject!, error: NSError!) -> Void in
  if error == nil {
    // result is "Hello world!"
  }
}

使用Mailgun发送邮件的示例代码段。

var Mailgun = require('mailgun');
Mailgun.initialize('myDomainName', 'myAPIKey');

Mailgun.sendEmail({
  to: "email@example.com",
  from: "Mailgun@CloudCode.com",
  subject: "Hello from Cloud Code!",
  text: "Using Parse and Mailgun is great!"
}, {
  success: function(httpResponse) {
    console.log(httpResponse);
    response.success("Email sent!");
  },
  error: function(httpResponse) {
    console.error(httpResponse);
    response.error("Uh oh, something went wrong");
  }
});

我需要导入一个模块吗?它一直在给我报错。 - Noah Barsky
var Mailgun = require('mailgun'); - picciano
我有相同的代码,但仍然出现错误。 在Swift中,字符串必须使用""而不是'。 - Noah Barsky
不是的,这是一个使用 Parse.com 的 CloudCode 函数。它是一种基于 JavaScript 的语言。你的问题提到了也要使用 Parse,所以我建议这个作为替代方案。你也可以直接从 Swift 代码中使用 Mailgun,但这样会更好地控制你的 API 密钥。 - picciano
这是Javascript代码。 - Unome
1
有没有关于如何将Mailgun与Swift集成的好文档?@picciano - Unome

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接