---
title: "ios 发邮件"
author: "xiaojunhu"
date: "2012-03-01T22:42:39Z"
tags: []
categories: ["移动开发"]
slug: "ios"
draft: false
lastmod: "2012-03-01T22:42:39Z"
id: 1434831
url: "https://xiaojunhu.iteye.com/blog/1434831"
---

1.新建立一个项目,view based application(with storyboard.ARC)

2.需要引入UIMessage Library ,如下图

 

[![添加library](http://blog.zfcms.com/wp-content/uploads/2012/01/27AA7DD7-4D3E-4CCC-9752-9635980D47DA-300x144.png "27AA7DD7-4D3E-4CCC-9752-9635980D47DA")](http://blog.zfcms.com/wp-content/uploads/2012/01/27AA7DD7-4D3E-4CCC-9752-9635980D47DA.png)

 

3.编辑ViewController.h文件

如下

 

#import &lt;UIKit/UIKit.h&gt;  
#import &lt;MessageUI/MessageUI.h&gt;  
@interface ViewController : UIViewController &lt;MFMailComposeViewControllerDelegate&gt;

-(IBAction)sendMail:(id)sender;  
@end

4.在ViewController.m文件中添加如下方法

 

-(IBAction)sendMail:(id)sender  
{  
if (\[MFMailComposeViewController canSendMail]) {  
MFMailComposeViewController \*mail = \[\[MFMailComposeViewController alloc] init];  
mail.mailComposeDelegate = self;  
\[mail setSubject:@"Apple , Welcome to china."];  
NSArray \*toRecipients = \[NSArray arrayWithObjects:@"bu.xianggang@gmail.com", nil];  
\[mail setToRecipients:toRecipients];  
\[mail setCcRecipients:toRecipients];

NSString \*emailBody = @”hello apple”;

\[mail setMessageBody:emailBody isHTML:NO];  
mail.modalPresentationStyle = UIModalPresentationFormSheet;  
\[self presentModalViewController:mail animated:YES];  
} else {  
UIAlertView \*alert = \[\[UIAlertView alloc] initWithTitle:@”ERROR” message:@”Email is not supported on your device” delegate:self cancelButtonTitle:@”Cancel” otherButtonTitles: nil];  
\[alert show];  
}  
}  
\-(void)mailComposeController:(MFMailComposeViewController \*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError \*)error  
{  
switch (result) {  
case MFMailComposeResultCancelled:  
NSLog(@”Cancelled”);  
break;  
case MFMailComposeResultSaved:  
NSLog(@”Message saved in drafts folder”);  
break;

case MFMailComposeResultSent:  
NSLog(@”Message is sent”);  
break;

case MFMailComposeResultFailed:  
NSLog(@”Message not sent due to error”);  
break;  
default:  
NSLog(@”Mail not sent”);  
break;  
}  
\[self dismissModalViewControllerAnimated:YES];  
}

OK,大功搞成.