如何从iPhone应用程序发送邮件

时间:2022-01-12 07:08:05

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:

我想从我的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]];

So how can I send an email from my app?

那么,我如何从我的应用程序发送电子邮件呢?

11 个解决方案

#1


431  

On iOS 3.0 and later you should use the MFMailComposeViewController class, and the MFMailComposeViewControllerDelegate protocol, that is tucked away in the MessageUI framework.

在ios3.0上,稍后您应该使用MFMailComposeViewController类和MFMailComposeViewControllerDelegate协议,它隐藏在MessageUI框架中。

First add the framework and import:

首先添加框架并导入:

#import <MessageUI/MFMailComposeViewController.h>

Then, to send a message:

然后,发送消息:

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

Then the user does the work and you get the delegate callback in time:

然后用户完成工作,你及时得到委托回调:

- (void)mailComposeController:(MFMailComposeViewController*)controller  
          didFinishWithResult:(MFMailComposeResult)result 
                        error:(NSError*)error;
{
  if (result == MFMailComposeResultSent) {
    NSLog(@"It's away!");
  }
  [self dismissModalViewControllerAnimated:YES];
}

Remember to check if the device is configured for sending email:

请记住检查设备是否配置为发送电子邮件:

if ([MFMailComposeViewController canSendMail]) {
  // Show the composer
} else {
  // Handle the error
}

#2


61  

MFMailComposeViewController is the way to go after the release of iPhone OS 3.0 software. You can look at the sample code or the tutorial I wrote.

MFMailComposeViewController是实现iPhone OS 3.0软件发布的方法。您可以查看示例代码或我编写的教程。

#3


19  

A few things I'd like to add here:

这里我想补充几点:

  1. Using the mailto URL won't work in the simulator as mail.app isn't installed on the simulator. It does work on device though.

    使用mailto URL在模拟器中不能作为邮件使用。app没有安装在模拟器上。不过它在设备上也能工作。

  2. There is a limit to the length of the mailto URL. If the URL is larger than 4096 characters, mail.app won't launch.

    mailto URL的长度是有限制的。如果URL大于4096个字符,邮件。应用程序不会启动。

  3. There is a new class in OS 3.0 that lets you send an e-mail without leaving your app. See the class MFMailComposeViewController.

    OS 3.0中有一个新的类,可以让你发送电子邮件而不用离开你的应用程序。

#4


13  

If you want to send email from your application, the above code is the only way to do it unless you code your own mail client (SMTP) inside your app, or have a server send the mail for you.

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

For example, you could code your app to invoke a URL on your server which would send the mail for you. Then you simply call the URL from your code.

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

Note that with the above code you can't attach anything to the email, which the SMTP client method would allow you to do, as well as the server-side method.

注意,对于上面的代码,您不能将任何内容附加到电子邮件,SMTP客户端方法允许您这样做,以及服务器端方法。

#5


12  

Below code is used in my application to send email with an attachment here the attachments is an image .You can send any type of file only thing is to keep in mind is that you had to specify the correct 'mimeType'

下面的代码在我的应用程序中用于发送带有附件的电子邮件附件是一个图片。你可以发送任何类型的文件,唯一要记住的是你必须指定正确的“mimeType”

add this to your .h file

将它添加到.h文件中

#import <MessageUI/MFMailComposeViewController.h>

Add MessageUI.framework to your project file

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

Delegate method is as shown below

委托方法如下所示

  -(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
    if (result == MFMailComposeResultSent) {
        NSLog(@"It's away!");
    }
    [self dismissModalViewControllerAnimated:YES];
}

#6


11  

This is the code which can help u but dont forget to include message ui framewark and include delegates method MFMailComposeViewControllerDelegate

这段代码可以帮助您,但不要忘记包含message ui framewark,并包含委托方法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];
    }

#7


4  

To send an email from iPhone application you need to do below list of task.

要从iPhone应用程序发送电子邮件,您需要完成以下任务列表。

Step 1: Import #import <MessageUI/MessageUI.h> In your controller class where you want to send an email.

步骤1:导入# Import 在控制器类中,你想要发送电子邮件。

Step 2: Add the delegate to your controller like shown below

步骤2:将委托添加到控制器中,如下所示

 @interface <yourControllerName> : UIViewController <MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate>

Step 3: Add below method for send email.

步骤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.
}
}

Step 4: Implement MFMailComposeViewController Delegate

步骤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;
}
}

#8


3  

Swift 2.2. Adapted from Esq's answer

斯威夫特2.2。改编自收的回答

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)
    }
}

Client code :

客户机代码:

var ms: MailSender?

@IBAction func onSendPressed(sender: AnyObject) {
    ms = MailSender(parentVC: self)
    let title = "Title"
    let messageBody = "https://*.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)
}

#9


2  

Swift 2.0

斯威夫特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)")

        //------------------------------------------------
    }
}

#10


1  

Heres a Swift version:

这是快速版:

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)
    }
}

Source

#11


0  

I wrote a simple wrapper called KRNSendEmail that simplify sending email to one method call.

The KRNSendEmail is well documented and added to CocoaPods.

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

我编写了一个名为KRNSendEmail的简单包装器,它简化了向一个方法调用发送电子邮件。KRNSendEmail有很好的文献记载并被添加到可可粉中。https://github.com/ulian-onua/KRNSendEmail

#1


431  

On iOS 3.0 and later you should use the MFMailComposeViewController class, and the MFMailComposeViewControllerDelegate protocol, that is tucked away in the MessageUI framework.

在ios3.0上,稍后您应该使用MFMailComposeViewController类和MFMailComposeViewControllerDelegate协议,它隐藏在MessageUI框架中。

First add the framework and import:

首先添加框架并导入:

#import <MessageUI/MFMailComposeViewController.h>

Then, to send a message:

然后,发送消息:

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

Then the user does the work and you get the delegate callback in time:

然后用户完成工作,你及时得到委托回调:

- (void)mailComposeController:(MFMailComposeViewController*)controller  
          didFinishWithResult:(MFMailComposeResult)result 
                        error:(NSError*)error;
{
  if (result == MFMailComposeResultSent) {
    NSLog(@"It's away!");
  }
  [self dismissModalViewControllerAnimated:YES];
}

Remember to check if the device is configured for sending email:

请记住检查设备是否配置为发送电子邮件:

if ([MFMailComposeViewController canSendMail]) {
  // Show the composer
} else {
  // Handle the error
}

#2


61  

MFMailComposeViewController is the way to go after the release of iPhone OS 3.0 software. You can look at the sample code or the tutorial I wrote.

MFMailComposeViewController是实现iPhone OS 3.0软件发布的方法。您可以查看示例代码或我编写的教程。

#3


19  

A few things I'd like to add here:

这里我想补充几点:

  1. Using the mailto URL won't work in the simulator as mail.app isn't installed on the simulator. It does work on device though.

    使用mailto URL在模拟器中不能作为邮件使用。app没有安装在模拟器上。不过它在设备上也能工作。

  2. There is a limit to the length of the mailto URL. If the URL is larger than 4096 characters, mail.app won't launch.

    mailto URL的长度是有限制的。如果URL大于4096个字符,邮件。应用程序不会启动。

  3. There is a new class in OS 3.0 that lets you send an e-mail without leaving your app. See the class MFMailComposeViewController.

    OS 3.0中有一个新的类,可以让你发送电子邮件而不用离开你的应用程序。

#4


13  

If you want to send email from your application, the above code is the only way to do it unless you code your own mail client (SMTP) inside your app, or have a server send the mail for you.

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

For example, you could code your app to invoke a URL on your server which would send the mail for you. Then you simply call the URL from your code.

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

Note that with the above code you can't attach anything to the email, which the SMTP client method would allow you to do, as well as the server-side method.

注意,对于上面的代码,您不能将任何内容附加到电子邮件,SMTP客户端方法允许您这样做,以及服务器端方法。

#5


12  

Below code is used in my application to send email with an attachment here the attachments is an image .You can send any type of file only thing is to keep in mind is that you had to specify the correct 'mimeType'

下面的代码在我的应用程序中用于发送带有附件的电子邮件附件是一个图片。你可以发送任何类型的文件,唯一要记住的是你必须指定正确的“mimeType”

add this to your .h file

将它添加到.h文件中

#import <MessageUI/MFMailComposeViewController.h>

Add MessageUI.framework to your project file

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

Delegate method is as shown below

委托方法如下所示

  -(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
    if (result == MFMailComposeResultSent) {
        NSLog(@"It's away!");
    }
    [self dismissModalViewControllerAnimated:YES];
}

#6


11  

This is the code which can help u but dont forget to include message ui framewark and include delegates method MFMailComposeViewControllerDelegate

这段代码可以帮助您,但不要忘记包含message ui framewark,并包含委托方法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];
    }

#7


4  

To send an email from iPhone application you need to do below list of task.

要从iPhone应用程序发送电子邮件,您需要完成以下任务列表。

Step 1: Import #import <MessageUI/MessageUI.h> In your controller class where you want to send an email.

步骤1:导入# Import 在控制器类中,你想要发送电子邮件。

Step 2: Add the delegate to your controller like shown below

步骤2:将委托添加到控制器中,如下所示

 @interface <yourControllerName> : UIViewController <MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate>

Step 3: Add below method for send email.

步骤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.
}
}

Step 4: Implement MFMailComposeViewController Delegate

步骤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;
}
}

#8


3  

Swift 2.2. Adapted from Esq's answer

斯威夫特2.2。改编自收的回答

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)
    }
}

Client code :

客户机代码:

var ms: MailSender?

@IBAction func onSendPressed(sender: AnyObject) {
    ms = MailSender(parentVC: self)
    let title = "Title"
    let messageBody = "https://*.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)
}

#9


2  

Swift 2.0

斯威夫特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)")

        //------------------------------------------------
    }
}

#10


1  

Heres a Swift version:

这是快速版:

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)
    }
}

Source

#11


0  

I wrote a simple wrapper called KRNSendEmail that simplify sending email to one method call.

The KRNSendEmail is well documented and added to CocoaPods.

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

我编写了一个名为KRNSendEmail的简单包装器,它简化了向一个方法调用发送电子邮件。KRNSendEmail有很好的文献记载并被添加到可可粉中。https://github.com/ulian-onua/KRNSendEmail