[Objective-C] Send mail with attachments

Hi all,
with these lines of code you can use Apple iOS Mail system to send an email with an attachment!

It’s so easy that i don’t know this method!

First, import MessageUI framework, after include in your header file (.h) the import to the framework:

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]#import messageui/MessageUI.h[/code]

and set the delegate to

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]mfmailcomposeviewcontrollerdelegate[/code]

Now, create a button in your view and attach mailil function!

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]- (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult: (MFMailComposeResult)result error:(NSError*)error {
[self dismissModalViewControllerAnimated:YES];
}

– (IBAction) mailIt {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

[picker setSubject:@"This is the subject"];

UIImage *roboPic = [UIImage imageNamed:@"anImage.jpg"];
NSData *imageData = UIImageJPEGRepresentation(roboPic, 1);
[picker addAttachmentData:imageData mimeType:@"image/jpg" fileName:@"anImage.jpg"];

NSString *emailBody = @"This is the email body!!";
[picker setMessageBody:emailBody isHTML:YES];

[self presentModalViewController:picker animated:YES];
[picker release];
}[/code]

done!

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.