我想用我的iPhone应用程序发送一封电子邮件。我听说iOS SDK没有电子邮件API。我不想使用下面的代码,因为它将退出我的应用程序:
NSString *url = [NSString stringWithString: @"mailto:foo@example.com?cc=bar@example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
那么我如何从我的应用程序发送电子邮件呢?
以下是Swift版本:
import MessageUI
class YourVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if MFMailComposeViewController.canSendMail() {
var emailTitle = "Vea Software Feedback"
var messageBody = "Vea Software! :) "
var toRecipents = ["pj@veasoftware.com"]
var mc:MFMailComposeViewController = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setSubject(emailTitle)
mc.setMessageBody(messageBody, isHTML: false)
mc.setToRecipients(toRecipents)
self.presentViewController(mc, animated: true, completion: nil)
} else {
println("No email account found")
}
}
}
extension YourVC: MFMailComposeViewControllerDelegate {
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
switch result.value {
case MFMailComposeResultCancelled.value:
println("Mail Cancelled")
case MFMailComposeResultSaved.value:
println("Mail Saved")
case MFMailComposeResultSent.value:
println("Mail Sent")
case MFMailComposeResultFailed.value:
println("Mail Failed")
default:
break
}
self.dismissViewControllerAnimated(false, completion: nil)
}
}
源
斯威夫特2.2。改编自Esq的回答
import Foundation
import MessageUI
class MailSender: NSObject, MFMailComposeViewControllerDelegate {
let parentVC: UIViewController
init(parentVC: UIViewController) {
self.parentVC = parentVC
super.init()
}
func send(title: String, messageBody: String, toRecipients: [String]) {
if MFMailComposeViewController.canSendMail() {
let mc: MFMailComposeViewController = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setSubject(title)
mc.setMessageBody(messageBody, isHTML: false)
mc.setToRecipients(toRecipients)
parentVC.presentViewController(mc, animated: true, completion: nil)
} else {
print("No email account found.")
}
}
func mailComposeController(controller: MFMailComposeViewController,
didFinishWithResult result: MFMailComposeResult, error: NSError?) {
switch result.rawValue {
case MFMailComposeResultCancelled.rawValue: print("Mail Cancelled")
case MFMailComposeResultSaved.rawValue: print("Mail Saved")
case MFMailComposeResultSent.rawValue: print("Mail Sent")
case MFMailComposeResultFailed.rawValue: print("Mail Failed")
default: break
}
parentVC.dismissViewControllerAnimated(false, completion: nil)
}
}
客户端代码:
var ms: MailSender?
@IBAction func onSendPressed(sender: AnyObject) {
ms = MailSender(parentVC: self)
let title = "Title"
let messageBody = "https://stackoverflow.com/questions/310946/how-can-i-send-mail-from-an-iphone-application this question."
let toRecipents = ["foo@bar.com"]
ms?.send(title, messageBody: messageBody, toRecipents: toRecipents)
}