Skip to content

Instantly share code, notes, and snippets.

@benvium
Created May 11, 2012 08:53
Show Gist options
  • Save benvium/2658497 to your computer and use it in GitHub Desktop.
Save benvium/2658497 to your computer and use it in GitHub Desktop.
Sending a file as an attachment via email from an iOS app. Add to a ViewController subclass
// NOTE YOU MUST ADD THE FRAMEWORK 'MessageUI' to your project.
// MyViewController.h
//-------------------
#import <MessageUI/MessageUI.h>
@interface MyViewController : UIViewController <MFMailComposeViewControllerDelegate>
// MyViewController.m
//-------------------
- (IBAction)sendFileFromDocumentFolderViaEmail:(id) sender {
// get date as a string
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"dd:MM:yyyy"];
NSDate *now = [NSDate date];
NSString* timeString = [dateFormat stringFromDate:now];
//NSArray *array = [[NSArray alloc] initWithObjects:@"myemail@gmail.com", nil];
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"A File Sent By Email"];
[controller setMessageBody:@"Here's a file" isHTML:NO];
// Get the documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"console.log"];
NSData* file = [NSData dataWithContentsOfFile:logPath];
NSString* filename = [timeString stringByAppendingString:@"-log.txt"];
[controller addAttachmentData:file mimeType:@"text/plain" fileName:filename];
[self presentModalViewController:controller animated:YES];
[controller release];
}
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
[self becomeFirstResponder];
[self dismissModalViewControllerAnimated:YES];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment