发送邮件

在创建PDF这篇文章中,我们在Documents目录中创建了一个PDF。这里,我们就把这个PDF作为邮件的附件。

 

首先,需要将MessageUI.framework加入到项目中。

 

头文件:

 

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

@interface mailViewController : UIViewController <MFMailComposeViewControllerDelegate> {
	
}

- (IBAction)sendMail;
- (void)displayComposerSheet;

@end

 

实现文件:

 

#import "mailViewController.h"

@implementation mailViewController

- (IBAction)sendMail { 
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController")); 
    if (mailClass != nil) { 
        if ([mailClass canSendMail]) { 
            [self displayComposerSheet]; 
        }        
    } 
} 

- (void)displayComposerSheet { 
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init]; 
    picker.title = @"New Message"; 
    picker.mailComposeDelegate = self; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"yyyy/MM/dd"]; 
    NSDate *date = [[NSDate alloc] init]; 
    NSString *content=[[NSString alloc] 
                       initWithFormat:@"App:1.0.iOS:%@ Date:%@", 
                       [[UIDevice currentDevice] systemVersion], [dateFormatter stringFromDate:date]]; 
    [date release]; 
    [dateFormatter release];	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"tmp.pdf"];
	NSData *myData = [NSData dataWithContentsOfFile:appFile];
	[picker addAttachmentData:myData mimeType:@"pdf" fileName:@"ceshi.pdf"];
    [picker setMessageBody:content isHTML:NO]; 
    [content release]; 
    [self presentModalViewController:picker animated:YES]; 
    [picker release]; 
} 

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {    
	switch(result) { 
		case MFMailComposeResultCancelled: 
            NSLog(@"cancelled");
            break; 
        case MFMailComposeResultSaved: 
            NSLog(@"saved");
            break; 
        case MFMailComposeResultSent: 
            NSLog(@"sent"); 
            break; 
        case MFMailComposeResultFailed: 
			NSLog(@"failed");
            break; 
        default: 
			NSLog(@"not sent");
            break; 
    } 
    [self dismissModalViewControllerAnimated:YES]; 
}

@end

你可能感兴趣的:(ios,邮件,iPhone)