使用Swift发送电子邮件

Noa*_*sky 41 email ios parse-platform mailgun swift

你会如何在应用程序中发送swift电子邮件?比如说,例如你的用户希望在Parse(或不是)的社交媒体应用程序中重置他们的密码,但是你不想使用MessageUI,因为你希望它是自动的.我已经做了一些研究,发现它可以用mailgun,但我无法弄清楚如何使用它与swift和XCode 6.你能帮帮我吗?

Moh*_*din 87

你当然可以.

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)

    }
}
Run Code Online (Sandbox Code Playgroud)

来源Andrew Bancroft

  • 从问题:"但你不想使用MessageUI,因为你希望它是自动的" (10认同)
  • 看起来_very_熟悉的https://www.andrewcbancroft.com/2014/08/25/send-email-in-app-using-mfmailcomposeviewcontroller-with-swift/ (6认同)

pic*_*ano 6

Parse支持开箱即用的Mailgun和Mandrill.查看他们的文档

您需要编写CloudCode函数,然后从您的应用程序中调用它.

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

使用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");
  }
});
Run Code Online (Sandbox Code Playgroud)