文档章节

iOS SDK: Send E-mail In-App

mickelfeng
 mickelfeng
发布于 2014/07/10 14:12
字数 1122
阅读 25
收藏 0

In this iOS SDK tutorial, I'll demonstrate how to allow your users to send e-mail without leaving your application using the MFMailComposeViewController class. We will setup an e-mail template with recipients, a subject, body text, and even an image attachment.

The iOS SDK provides an easy to use, standard interface to allow your users to send and edit e-mail from within your own application. To do so, you will need to use theMFMailComposeViewController class. This view controller displays a standard mail interface and also provides the functionality to respond to user events performed on that interface. For instance, you the class will notify you if the user hit "send" or "cancel".

Note: MFMailComposeViewController is only available on iOS 3.0 or later.

So, how does it work? Follow the steps in this tutorial to find out.

Step 1: Create a New Xcode Project

Open Xcode and select “Create a new Xcode project”. Select View-based Application and then click Next. Enter a name for your project. I called mine @”Mail”. Enter your Company Identifier and make sure you selected "iPhone" forDevice Family, because we are going to make an iPhone app. If you are done, clickNext. Choose a place to save your project and click Create.

    

Step 2: Add the Mail Button

Open the "MailViewController.xib" file and drag a button into the view. Set the title of the button to "Mail". Now select the middle button of the Editor to show the “Assistant editor”, so we can add an action to the button we just created.

    

Select the button and CTRL-drag to the “MailViewController.h”. In the pop-up that is displayed, enter “openMail” for name and make sure to set the connection type to “Action”, because we want to make an action and not an outlet.

    Connection

Step 3: Import the MessageUI Framework

In the navigator area of Xcode 4, select the project name. Next, select the current target (“Mail” in this case), and then select the “Build Phases” tab. Expand the “Link Binary With Libraries” option, and then click the “+” button to add a new framework. Type “message″ into the search box, and select the MessageUI.framework option that appears in the list. Click “Add” to include this framework in the linking phase of your project.

Now that you have added the MessageUI framework into your project, you need to import that framework into the view controller that will use theMFMailComposeViewController, so, in our case, MailViewController.h.

Go to this file and modify the code to read as follows:

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
 
@interface MailViewController : UIViewController <MFMailComposeViewControllerDelegate>
 
- (IBAction)openMail:(id)sender;
 
@end

As you can see, we also declared the MFMaileComposeViewControllerDelegate in the above code. We will use this delegate to see the result of the mail.

Step 4: Add Project Resources

Drag the following image to the “Supporting Files” folder in your project. Make sure “Copy items into destination group’s folder (if needed)” is checked before clickingfinish.

    MobileTuts+ logo

Step 5: Check if Device is Able to Send E-mail

Open the “MailViewController.m” file and scroll down to the openMail: action and modify the code to read as follows:

- (IBAction)openMail:(id)sender 
{
    if ([MFMailComposeViewController canSendMail])
    {
     
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
 
}

Here we check if the current device is able to send e-mail with the canSendMailclass method of MFMailComposeViewController. You should always call this method before you open the mail interface. If the device is not able to send e-mail, you should notify the user (I've used a UIAlertView for this).

Step 6: Show the Mail Interface

If the device is able to send e-mail, we display the mail interface. Go to theopenMail: action and modify the code to read as follows:

- (IBAction)openMail:(id)sender 
{
    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
         
        mailer.mailComposeDelegate = self;
         
        [mailer setSubject:@"A Message from MobileTuts+"];
         
        NSArray *toRecipients = [NSArray arrayWithObjects:@"fisrtMail@example.com", @"secondMail@example.com", nil];
        [mailer setToRecipients:toRecipients];
         
        UIImage *myImage = [UIImage imageNamed:@"mobiletuts-logo.png"];
        NSData *imageData = UIImagePNGRepresentation(myImage);
        [mailer addAttachmentData:imageData mimeType:@"image/png" fileName:@"mobiletutsImage"]; 
         
        NSString *emailBody = @"Have you seen the MobileTuts+ web site?";
        [mailer setMessageBody:emailBody isHTML:NO];
         
        [self presentModalViewController:mailer animated:YES];
         
        [mailer release];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
 
}

First we create a MFMaileComposeViewController and call it “mailer”. We set themailComposeDelegate to self, so we can see the result of the mail. The subject is set to “A Message from MobileTuts+”. As you can see, the toRecipients is of the type NSArray. This is because you can add multiple recipients. I added two fake email addresses, but of course you can put any address you like. After that, we store an image as an NSData object, because we cant send a UIImage directly. Then we add the NSData object as an attachment to our e-mail. We set the type to a png image and the fileName to “mobiletutsImage”. This means that when the receiver saves the image, it will be saved under the name "mobiletutsImage". The last thing we do is show the mailer before releasing the mailer object.

Step 7: Check the Result and Dismiss the View

You need to manually dismiss the mail interface in response to a delegate method call. Add the following code under the openMail: action:

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{   
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled: you cancelled the operation and no email message was queued.");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved: you saved the email message in the drafts folder.");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail send: the email message is queued in the outbox. It is ready to send.");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail failed: the email message was not saved or queued, possibly due to an error.");
            break;
        default:
            NSLog(@"Mail not sent.");
            break;
    }
 
        // Remove the mail view
    [self dismissModalViewControllerAnimated:YES];
}

In this delegate method, we check the result of having displayed the mail view controller with a switch statement and then dismiss the view controller with an animation. In the above code, I've simply printed an NSLog message with the results, but the point is that you could respond dynamically to the user's action.

BONUS: Make it Work for iPad

On an iPad it looks nice to show the mail interface in a page sheet presentation. You can do that by adding the following line of code just above [self presentModalViewController:mailer animated:YES];:

mailer.modalPresentationStyle = UIModalPresentationPageSheet;

iPad mail interface

Wrap Up

I hope you enjoyed this tutorial. If you have any feedback or requests for additional iOS content from me, please leave a comment below!

http://code.tutsplus.com/tutorials/mfmailcomposeviewcontroller--mobile-7982

本文转载自:http://code.tutsplus.com/tutorials/mfmailcomposeviewcontroller--mobile-7982

mickelfeng

mickelfeng

粉丝 237
博文 2790
码字总数 604288
作品 0
成都
高级程序员
私信 提问
用python编写ios工程自动编译、打包ipa等脚本

第一次使用python请先看:http://my.oschina.net/LangZiAiFer/blog/298763 代码管理我用的是Git; 工程clone如下: 需要import import os import time import json import commands import s......

浪子艾菲儿
2014/08/08
3.2K
0
学习如何针对iOS 7进行开发?

  iOS 7已经发布了六个测试版,除了beta 6进行了小幅修正外,其他几个测试版都有不小的改动。昨天有消息说苹果将在9月10日发布iOS 7正式版,那么GM版很快将会与开发者见面。在iOS 7来临前夕...

fangzhou99
2013/09/17
420
0
ArcGIS for iOS 开发系列(1) – 基本概念

1.1 iOS简介 2006年苹果公司发布了智能手机iPhone,卓越的外形设计和新颖的触摸式交互,令其迅速风靡全球,随后发布的平板电脑iPad同样也取得了巨大成功,二者所搭载的都是iOS智能移动操作系...

长平狐
2012/11/28
881
0
使用 Countly 来分析 Apple Watch 统计数据

期待已久的 Apple Watch 在上市当日预购了将近一百万,已经开始在全球发货了。考虑到 Apple Watch 的销售量已经在一天内达到了,我们可以说智能手表将会是用户生活中一个更重要的部分,尤其是...

oschina
2015/05/19
1K
1
Phonegap各类商业插件

【Phonegap商业插件服务】[目前插件已经支持到Phonegap最新版本] 1.phonegap-百度社会化分享-andriod插件 v2.0 【该插件支持微信分享和朋友圈分享,qq好友分享,微博分享】 2.phonegap百度社...

夜澜小雨
2015/07/15
1K
0

没有更多内容

加载失败,请刷新页面

加载更多

手写RPC框架指北另送贴心注释代码一套

Angular8正式发布了,Java13再过几个月也要发布了,技术迭代这么快,框架的复杂度越来越大,但是原理是基本不变的。所以沉下心看清代码本质很重要,这次给大家带来的是手写RPC框架。 完整代码...

全菜工程师小辉
16分钟前
3
0
【Java】开发收货

简介 谨以此篇,记载开发过程中的一些tips。 编译器 【Shift + F6】可实现变量的联动修改。

Areya
33分钟前
5
0
DOM官方定义

DOM Document Object Model 文档对象模型 DOM的官方定义:W3C的DOM,可以使程序或者脚本(JS或AS\JScript),动态的访问或者操作文档的内容、结构、样式。 DOM只是一个标准,操作网页的标准。...

前端老手
38分钟前
6
0
IT兄弟连 HTML5教程 HTML5的学习线路图 第一阶段学习网页制作

学习HTML5技术可并不是简单学会几个新增的标签而已,HTML5现在可以说是前端所有技术的代名词。需要学习的语言和工具不仅多,对于刚接触他们的新人会感觉很乱。另外,前端开发也会细分很多个开...

老码农的一亩三分地
40分钟前
6
0
可见性有序性,Happens-before来搞定

写在前面 上一篇文章并发 Bug 之源有三,请睁大眼睛看清它们 谈到了可见性/原子性/有序性三个问题,这些问题通常违背我们的直觉和思考模式,也就导致了很多并发 Bug 为了解决 CPU,内存,IO ...

tan日拱一兵
55分钟前
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部