iOS开发——发送邮件

声明:UnivCore原创博客,如若转载,请以超链接形式标明文章 原始出处、作者信息和本声明。http://blog.csdn.net/univcore/article/details/15028519


iOS开发中,要实现应用发送邮件的功能有多种方法。本文中介绍的邮件发送功能是由MessageUI Framework提供的,这个框架是iPhone SDK中最简单的框架。由一个类、一个视图控制器,一个protocol组成。

为了直观地演示,我们通过一个Step by  Step的Demo来阐述下这个方法的基本使用技巧。

首先,创建一个Single View的示例项目。这里,我创建了一个名为MailSystemDemo的Single View项目。然后在ViewController对应的xib中添加一个按钮,为该按钮实现一个响应的方法,方法中的内容暂时为空即可,稍后我们将把调用发送邮件方法的语句写入到此按钮方法中。

其次,正如前面介绍的,发送邮件的功能是由MessageUI Framework提供的,所以我们要在Buil Phases中添加MessageUI.framework框架。然后,在ViewController.h文件中加入如下代码,引入头文件并且采用MFMailComposeViewControllerDelegate协议。

#import <MessageUI/MFMailComposeViewController.h>

@interface ViewController : UIViewController <MFMailComposeViewControllerDelegate>

在ViewController.m文件中,实现如下发送邮件的核心方法:

- (void)sendEmail
{
    MFMailComposeViewController *sendMailViewController = [[MFMailComposeViewController alloc] init];
    sendMailViewController.mailComposeDelegate = self;
   
    // 设置邮件主题
    [sendMailViewController setSubject:@"Test Message"];
    
    /*
     * 设置收件人,收件人有三种
     */
    // 设置主收件人
    [sendMailViewController setToRecipients:[NSArray arrayWithObject:@"[email protected]"]];
    // 设置CC
    [sendMailViewController setCcRecipients:[NSArray arrayWithObject:@"[email protected]"]];
    // 设置BCC
    [sendMailViewController setBccRecipients:[NSArray arrayWithObject:@"[email protected]"]];
    
    /* 
     * 设置邮件主体,有两种格式 
     */
    // 一种是纯文本
    [sendMailViewController setMessageBody:@"Hello World!\nIs everything OK?" isHTML:NO];
    // 一种是HTML格式(HTML和纯文本两种格式按需求选择一种即可)
    //[mailVC setMessageBody:@"<HTML><B>Hello World!</B><BR/>Is everything OK?</HTML>" isHTML:YES];
    
    // 添加附件
    NSString *path = [[NSBundle mainBundle] pathForResource:@"feedback" ofType:@"png"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    [sendMailViewController addAttachmentData:data mimeType:@"image/png" fileName:@"feedback"];
    
    // 视图呈现
    [self presentViewController:sendMailViewController animated:YES completion:nil];
}


然后,我们在ViewController.m文件中实现一个MFMailComposeViewControllerDelegate协议中的方法,无论用户是否发送或取消发送,不论系统是否能够实现邮件发送 ,此方法都会被回调。

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result) {
        case MFMailComposeResultCancelled: {
            NSLog(@"Mail send canceled.");
            break;
        }
        case MFMailComposeResultSaved: {
            NSLog(@"Mail saved.");
            break;
        }
        case MFMailComposeResultSent: {
            NSLog(@"Mail sent.");
            break;
        }
        case MFMailComposeResultFailed: {
            NSLog(@"Mail sent Failed.");
            break;
        }
        default:
            break;
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

最后,我们在按钮的响应方法中调用发送邮件的方法。这里,我们需要对设备是否可以发送邮件做一个判断。如果用户已经在邮件客户端配置好了账户,那我们直接调用发送邮件的方法,否则我们就得先用[[UIApplication sharedApplication] openURL:]方法来加载系统的邮件客户端,让用户先进行邮箱的配置。

- (IBAction)sendEmailBtnPressed:(id)sender
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (mailClass != nil)
    {
        if ([mailClass canSendMail])
        {
            [self sendEmail];   // 调用发送邮件的方法
        }
        else {
            [self launchMailAppOnDevice];   // 调用客户端邮件程序
        }
    }
    else {
        [self launchMailAppOnDevice];    // 调用客户端邮件程序
    }
    
}

调用系统邮件客户端进行邮箱配置的方法如下:

-(void)launchMailAppOnDevice
{
    NSString *recipients = @"mailto:[email protected]&subject=my email!";
    //@"mailto:[email protected][email protected],[email protected]&subject=my email!";
    NSString *body = @"&body=email body!";
    NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
    email = [email stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
}

到这里,实现发送邮件功能的代码就都完成了,你现在就可以尝试运行一下程序,对其进行测试。

这种方法的突出优点就是简单方便,而且功能全面,可以满足大部分App的需求。当然它也有一个明显的劣势,iOS系统替我们提供了一个mail中的UI,而我们却完全无法对其进行订制,这会让那些定制化成自己风格的App望而却步,因为这样使用的话无疑太突兀了。


你可能感兴趣的:(ios开发,邮件发送,MessageUI)