我想用我的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]];
那么我如何从我的应用程序发送电子邮件呢?
在ios3.0及以后的版本中,你应该使用MFMailComposeViewController类,以及隐藏在MessageUI框架中的MFMailComposeViewControllerDelegate协议。
首先添加框架并导入:
#import <MessageUI/MFMailComposeViewController.h>
然后,发送一个消息:
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"My Subject"];
[controller setMessageBody:@"Hello there." isHTML:NO];
if (controller) [self presentModalViewController:controller animated:YES];
[controller release];
然后用户完成工作,你及时得到委托回调:
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
记得检查设备是否配置为发送电子邮件:
if ([MFMailComposeViewController canSendMail]) {
// Show the composer
} else {
// Handle the error
}
下面的代码在我的应用程序中用于发送带有附件的电子邮件这里的附件是一张图片,你可以发送任何类型的文件唯一需要记住的是你必须指定正确的mimeType
将此添加到.h文件中
#import <MessageUI/MFMailComposeViewController.h>
将MessageUI.framework添加到项目文件中
NSArray *paths = SSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"myGreenCard.png"];
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"Green card application"];
[controller setMessageBody:@"Hi , <br/> This is my new latest designed green card." isHTML:YES];
[controller addAttachmentData:[NSData dataWithContentsOfFile:getImagePath] mimeType:@"png" fileName:@"My Green Card"];
if (controller)
[self presentModalViewController:controller animated:YES];
[controller release];
委托方法如下所示
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
以下是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)
}
从iPhone应用程序发送电子邮件,你需要做下面的任务列表。
步骤1:导入# Import <MessageUI/MessageUI.h>在你想要发送电子邮件的控制器类中。
步骤2:添加委托到您的控制器如下所示
@interface <yourControllerName> : UIViewController <MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate>
步骤3:添加以下发送电子邮件的方法。
- (void) sendEmail {
// Check if your app support the email.
if ([MFMailComposeViewController canSendMail]) {
// Create an object of mail composer.
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
// Add delegate to your self.
mailComposer.mailComposeDelegate = self;
// Add recipients to mail if you do not want to add default recipient then remove below line.
[mailComposer setToRecipients:@[<add here your recipient objects>]];
// Write email subject.
[mailComposer setSubject:@“<Your Subject Here>”];
// Set your email body and if body contains HTML then Pass “YES” in isHTML.
[mailComposer setMessageBody:@“<Your Message Body>” isHTML:NO];
// Show your mail composer.
[self presentViewController:mailComposer animated:YES completion:NULL];
}
else {
// Here you can show toast to user about not support to sending email.
}
}
步骤4:实现MFMailComposeViewController Delegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(nullable NSError *)error {
[controller dismissViewControllerAnimated:TRUE completion:nil];
switch (result) {
case MFMailComposeResultSaved: {
// Add code on save mail to draft.
break;
}
case MFMailComposeResultSent: {
// Add code on sent a mail.
break;
}
case MFMailComposeResultCancelled: {
// Add code on cancel a mail.
break;
}
case MFMailComposeResultFailed: {
// Add code on failed to send a mail.
break;
}
default:
break;
}
}