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

Khu*_*shi 243 email iphone cocoa-touch ios

我想从我的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]];
Run Code Online (Sandbox Code Playgroud)

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

Pey*_*loW 431

在iOS 3.0及更高版本中,您应该使用隐藏在MessageUI框架中的MFMailComposeViewController类和MFMailComposeViewControllerDelegate协议.

首先添加框架并导入:

#import <MessageUI/MFMailComposeViewController.h>
Run Code Online (Sandbox Code Playgroud)

然后,发送消息:

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];
Run Code Online (Sandbox Code Playgroud)

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

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

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

if ([MFMailComposeViewController canSendMail]) {
  // Show the composer
} else {
  // Handle the error
}
Run Code Online (Sandbox Code Playgroud)

  • 要保存跳转,需要#import <MessageUI/MFMailComposeViewController.h> (71认同)
  • 请注意,因为这个答案是写的UIViewController的方法`presentModalViewController:animated:`和`dismissModalViewControllerAnimated:`已被标记为已弃用 - 而是基于块的替换方法`presentViewController:animated:completion:`和`dismissViewControllerAnimated:completion:`应该使用. (22认同)
  • 在IOS 6` [self presentModalViewController:controller animated:YES];`**替换为**`[self presentViewController:controller animated:YES completion:nil];`**和**`[self dismissModalViewControllerAnimated:YES]; `**替换为**`[self dismissViewControllerAnimated:YES completion:nil];` (18认同)
  • +1.这里提到了需要导入的框架(http://www.mobileorchard.com/new-in-iphone-30-tutorial-series-part-2-in-app-email-messageui/). (5认同)
  • 并且不要忘记在.h`中设置委托`@interface viewController:UIViewController <MFMailComposeViewControllerDelegate>` (2认同)

Mug*_*nth 61

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

  • Mugunth的精彩帖子.去哥们的方式! (2认同)

小智 19

我想在这里添加一些内容:

  1. 使用mailto URL将无法在模拟器中运行,因为模拟器上未安装mail.app.它确实在设备上工作.

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

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


Gen*_*ich 13

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

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

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


Kan*_*sad 12

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

将其添加到.h文件中

#import <MessageUI/MFMailComposeViewController.h>
Run Code Online (Sandbox Code Playgroud)

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];
Run Code Online (Sandbox Code Playgroud)

委托方法如下所示

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


小智 11

这是可以帮助你的代码但是不要忘记包含消息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];
    }
Run Code Online (Sandbox Code Playgroud)