243

I want to send an email from my iPhone application. I have heard that the iOS SDK doesn't have an email API. I don't want to use the following code because it will exit my application:

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]];

So how can I send an email from my app?

4

11 回答 11

429

在 iOS 3.0 及更高版本上,您应该使用隐藏在 MessageUI 框架中的MFMailComposeViewController类和协议。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
}
于 2009-10-03T10:32:34.790 回答
61

MFMailComposeViewController是 iPhone OS 3.0 软件发布之后的发展方向。您可以查看示例代码我编写的教程

于 2009-08-11T02:57:42.940 回答
20

我想在这里补充几点:

  1. 由于 mail.app 未安装在模拟器上,因此无法在模拟器中使用 mailto URL。它确实适用于设备。

  2. mailto URL 的长度有限制。如果 URL 大于 4096 个字符,mail.app 将不会启动。

  3. OS 3.0 中有一个新类,可让您在不离开应用程序的情况下发送电子邮件。请参阅 MFMailComposeViewController 类。

于 2009-07-26T20:57:42.460 回答
13

如果您想从您的应用程序发送电子邮件,除非您在应用程序中编写自己的邮件客户端 (SMTP),或者让服务器为您发送邮件,否则上述代码是唯一的方法。

例如,您可以编写应用程序以调用服务器上的 URL,该 URL 将为您发送邮件。然后,您只需从代码中调用 URL。

请注意,使用上面的代码,您无法将任何内容附加到电子邮件中,SMTP 客户端方法以及服务器端方法都允许您这样做。

于 2008-12-23T09:46:35.517 回答
12

下面的代码在我的应用程序中用于发送带有附件的电子邮件,附件是图像。您可以发送任何类型的文件,唯一要记住的是您必须指定正确的“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];
}
于 2012-09-21T07:06:04.873 回答
11

这是可以帮助您但不要忘记包含消息 ui 框架并包含委托方法 MFMailComposeViewControllerDelegate 的代码

-(void)EmailButtonACtion{

        if ([MFMailComposeViewController canSendMail])
        {
            MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
            controller.mailComposeDelegate = self;
            [controller.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigation_bg_iPhone.png"] forBarMetrics:UIBarMetricsDefault];
            controller.navigationBar.tintColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.0];
            [controller setSubject:@""];
            [controller setMessageBody:@" " isHTML:YES];
            [controller setToRecipients:[NSArray arrayWithObjects:@"",nil]];
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            UIImage *ui = resultimg.image;
            pasteboard.image = ui;
            NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(ui)];
            [controller addAttachmentData:imageData mimeType:@"image/png" fileName:@" "];
            [self presentViewController:controller animated:YES completion:NULL];
        }
        else{
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"alrt" message:nil delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil] ;
            [alert show];
        }

    }
    -(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
    {

        [MailAlert show];
        switch (result)
        {
            case MFMailComposeResultCancelled:
                MailAlert.message = @"Email Cancelled";
                break;
            case MFMailComposeResultSaved:
                MailAlert.message = @"Email Saved";
                break;
            case MFMailComposeResultSent:
                MailAlert.message = @"Email Sent";
                break;
            case MFMailComposeResultFailed:
                MailAlert.message = @"Email Failed";
                break;
            default:
                MailAlert.message = @"Email Not Sent";
                break;
        }
        [self dismissViewControllerAnimated:YES completion:NULL];
        [MailAlert show];
    }
于 2013-09-09T11:22:53.060 回答
4

斯威夫特 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)
}
于 2016-04-16T23:59:02.530 回答
4

要从 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:@“&lt;Your Subject Here>”];
    // Set your email body and if body contains HTML then Pass “YES” in isHTML.
    [mailComposer setMessageBody:@“&lt;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 委托

- (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;
}
}
于 2016-08-05T13:40:06.107 回答
2

斯威夫特 2.0

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?){
    if let error = error{
        print("Error: \(error)")
    }else{
        //NO Error
        //------------------------------------------------
        var feedbackMsg = ""

        switch result.rawValue {
        case MFMailComposeResultCancelled.rawValue:
            feedbackMsg = "Mail Cancelled"
        case MFMailComposeResultSaved.rawValue:
            feedbackMsg = "Mail Saved"
        case MFMailComposeResultSent.rawValue:
            feedbackMsg = "Mail Sent"
        case MFMailComposeResultFailed.rawValue:
            feedbackMsg = "Mail Failed"
        default:
            feedbackMsg = ""
        }

        print("Mail: \(feedbackMsg)")

        //------------------------------------------------
    }
}
于 2015-09-22T14:12:46.970 回答
1

这是一个 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)
    }
}

资源

于 2015-09-20T11:14:09.443 回答
0

我编写了一个名为 KRNSendEmail 的简单包装器,它简化了将电子邮件发送到一个方法调用的过程。

KRNSendEmail 有很好的文档记录并添加到 CocoaPods。

https://github.com/ulian-onua/KRNSendEmail

于 2017-03-24T20:42:06.133 回答