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

243

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

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

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
}

5
需要导入的框架在这里提到了(http://www.mobileorchard.com/new-in-iphone-30-tutorial-series-part-2-in-app-email-messageui/)。 - Dan Rosenstark
71
为了让你少走弯路,你需要导入以下代码:#import <MessageUI/MFMailComposeViewController.h>。 - TomH
22
请注意,自回答撰写之后,UIViewController的方法 presentModalViewController:animated:dismissModalViewControllerAnimated: 已被标记为弃用 - 应该使用基于块的替代方法 presentViewController:animated:completion:dismissViewControllerAnimated:completion:。请确保使用新的方法。 - user577537
2
不要忘记在.h中设置委托 @interface viewController : UIViewController <MFMailComposeViewControllerDelegate> - Nazir
18
在IOS 6中,将[self presentModalViewController:controller animated:YES]; 替换为 [self presentViewController:controller animated:YES completion:nil]; 并将 [self dismissModalViewControllerAnimated:YES]; 替换为 [self dismissViewControllerAnimated:YES completion:nil]; - Nazir
显示剩余5条评论

61

1
真的很棒。谢谢。我专门设计了一个视图来接受用户的电子邮件和主题。通过实现相同的代码,它再次显示类似的视图。我能否在视图控制器类中的按钮按下事件中调用委托方法?感谢您的帮助, Shibin - user169964
我已经下载了相同的示例代码,但它没有发送任何邮件。它只提示邮件已成功发送,但是没有收到任何邮件。我尝试添加MessageUI框架,但默认情况下它显示为红色,但应用程序仍然无法发送邮件。如有任何帮助,将不胜感激。我正在模拟器中测试该应用程序。 - Ravi shankar
模拟器无法发送电子邮件。 - malaki1974

20

这里有几件事情我想补充:

  1. 在模拟器中使用mailto URL是行不通的,因为模拟器上没有安装mail.app。但在设备上可以正常工作。

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

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


13
如果你想从应用程序中发送电子邮件,除非在应用程序内编写自己的邮件客户端(SMTP)或让服务器代表你发送邮件,否则上述代码是唯一的方法。
例如,你可以编写一个调用服务器URL以替你发送邮件的代码。然后,你只需从你的代码中调用该URL。
请注意,使用上述代码无法附加任何内容到邮件中,而SMTP客户端方法和服务器端方法都可以实现此功能。

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

11

这是可以帮助你的代码,但不要忘记包括消息界面框架和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];
    }

非常感谢!HTML正文的示例非常有用。 - Resty

4

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

步骤1:在希望发送电子邮件的控制器类中导入#import <MessageUI/MessageUI.h>

步骤2:像下面所示将委托添加到您的控制器中

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

步骤三:添加下面的方法以发送电子邮件。
 - (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.
}
}

第四步:实现 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;
}
}

这个回答提供了任何新的信息吗,这些信息在现有的回答中还没有包含? - Florian Koch

4

Swift 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://dev59.com/gXVC5IYBdhLWcg3wYQEp this question."
    let toRecipents = ["foo@bar.com"]
    ms?.send(title, messageBody: messageBody, toRecipents: toRecipents)
}

2

Swift 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)")

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

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

来源


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接