Attaching a mp3 file to email directly from app? - iphone

I am working on an app where, if the user selects a sound, they can email it to themselves from the app.
The attachment part 'appears' to work, however, when I send the email, the recipient has no attachment?
On the iPad/iPhone itself, it looks like it is attaching it when it comes to compose, but it is not working? :/
Here is the code I am using;
- (void)onSend:(id)sender{
int nIndex;
UIButton *btnSender = (UIButton *)sender;
NSLog( #"%d", btnSender.tag );
for ( int i = 0; i < [ m_aryFileName count ]; i++ ) {
if( i == ( btnSender.tag - 100 ) ){
nIndex = i;
}
}
NSString *strFileName = [ m_aryFileName objectAtIndex:nIndex ];
strFileName = [ strFileName stringByAppendingString:#".mp3" ];
NSData* nData = [ NSData dataWithContentsOfFile:strFileName ];
MFMailComposeViewController *pickerMail = [[MFMailComposeViewController alloc] init];
pickerMail.mailComposeDelegate = self;
[pickerMail setSubject:#"myMail Attachment"];
// Attach an image to the email
[pickerMail addAttachmentData:nData mimeType:#"audio/mp3" fileName:strFileName ];
// Fill out the email body text
NSString *emailBody = #"Here is your attachment";
[pickerMail setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:pickerMail animated:YES];
[pickerMail release];
}

try this code mate,
NSString *strFileName = [m_aryFileName objectAtIndex:nIndex];
strFileName = [strFileName stringByAppendingString:#".mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:strFileName];
NSData *nData = [[NSData alloc] initWithContentsOfURL:fileURL];
MFMailComposeViewController *pickerMail = [[MFMailComposeViewController alloc] init];
pickerMail.mailComposeDelegate = self;
[pickerMail setSubject:#"myMail Attachment"];
[pickerMail addAttachmentData:nData mimeType:#"audio/mpeg" fileName:strFileName ];
NSString *emailBody = #"Here is your attachment";
[pickerMail setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:pickerMail animated:YES];

Below code might be useful to you:
NSData *videoData = [NSData dataWithContentsOfURL:mediaUrl];
[mailcomposer addAttachmentData:videoData mimeType:#"video/mp4" fileName:#"Video"]

Try using a mime type of audio/mpeg instead. You can get this value by running the following code:
#import <MobileCoreServices/MobileCoreServices.h>
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
(__bridge CFStringRef)#"mp3",
NULL);
CFStringRef mimeTags = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType);
CFRelease(uti);
NSString *mediaType = [NSString stringWithString:(__bridge NSString *)mimeTags];
CFRelease(mimeTags);
How does that work?

if ([MFMailComposeViewController canSendMail] && m_pDataArray != nil)
{
NSString * pSongPath = [[NSBundle mainBundle] pathForResource:#"song" ofType"#"mp3"]; ;//get the file
MFMailComposeViewController * pMailComposer = [[MFMailComposeViewController alloc] init];
pMailComposer.mailComposeDelegate = self;
[pMailComposer setMessageBody:#"msg body" isHTML:NO];
NSURL * pFileUrl = [[[NSURL alloc] initFileURLWithPath:pSongPath] autorelease];
NSData * pData = [[[NSData alloc] initWithContentsOfURL:pFileUrl] autorelease];
[pMailComposer addAttachmentData:pData mimeType:#"audio/mpeg" fileName:#"song.mp3" ]];
[self presentModalViewController:pMailComposer animated:YES];
[pMailComposer release];
}
else
{
UIAlertView *pAlert = [[UIAlertView alloc] initWithTitle:#"Failure" message:#"Your device doesn't support the composer sheet" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[pAlert show];
[pAlert release];
pAlert = nil;
}
be sure that the file should have valid extension like .mp3 , in that case it will work properly

Related

Attach image to message composer in ios 6

How to attach an image to native message composer in ios6? I want to implement the same sharing via message function we can see in default photos app.
Thanks
For Mail:
MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
NSData *exportData = UIImageJPEGRepresentation(pic ,1.0);
[mailController addAttachmentData:exportData mimeType:#"image/jpeg" fileName:#"Photo.jpeg"];
[self presentModalViewController:mailController animated:YES];
The only way is through email currently. Unless you want to create a own MMS gateway to allow your app to support MMS..
For Message:
After reading up, instead of using MFMessageComposeViewController,you could UIApplication sharedApplication.
Example:
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.persistent = YES;
NSData *data = UIImageJPEGRepresentation(pic ,1.0);
pasteboard.image = [UIImage imageWithData:data];
NSString *phoneToCall = #"sms: 123-456-7890";
NSString *phoneToCallEncoded = [phoneToCall stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [[NSURL alloc] initWithString:phoneToCallEncoded];
[[UIApplication sharedApplication] openURL:url];
Longpress and click on Paste and message will be pasted...
Hope this helps... pic refers to the UIImage you are passing...
{
NSMutableDictionary * attachment = [[NSMutableDictionary alloc]init];
[attachment setObject: UIImageJPEGRepresentation(imageView.image,0.5) forKey:#"attachmentData"];
[attachment setObject: #"productImage.jpeg" forKey:#"attachmentFileName"];
[attachment setObject: #"jpeg" forKey:#"attachmentFileMimeType"];
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject: #"subject" forKey:#"subject"];
[params setObject: #"matterText" forKey:#"matterText"];
[params setObject: [[NSMutableArray alloc]initWithObjects:attachment, nil] forKey:#"attachments"];
}
#pragma mark - Sharing Via Email Related Methods
-(void)emailInfo:(NSMutableDictionary*)info
{
if (![MFMailComposeViewController canSendMail])
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Email Configuration"
message:#"We cannot send an email right now because your device's email account is not configured. Please configure an email account from your device's Settings, and try again."
delegate:nil
cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return;
}
MFMailComposeViewController *emailer = [[MFMailComposeViewController alloc] init];
emailer.mailComposeDelegate = self;
NSString * subject = [info objectForKey:#"subject"];
NSString * matterText = [info objectForKey:#"matterText"];
if(subject)
[emailer setSubject:subject];
if(matterText)
[emailer setMessageBody:matterText isHTML:NO];
NSMutableArray * attachments = [info objectForKey:#"attachments"];
if (attachments)
{
for (int i = 0 ; i < attachments.count ; i++)
{
NSMutableDictionary * attachment = [attachments objectAtIndex:i];
NSData * attachmentData = [attachment objectForKey:#"attachmentData"];
NSString * attachmentFileName = [attachment objectForKey:#"attachmentFileName"];
NSString * attachmentFileMimeType = [attachment objectForKey:#"attachmentFileMimeType"];
[emailer addAttachmentData:attachmentData mimeType:attachmentFileMimeType fileName:attachmentFileName];
}
}
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
emailer.modalPresentationStyle = UIModalPresentationPageSheet;
}
[self.navigationController.topViewController presentViewController:emailer animated:YES completion:nil];
}
I think you cant attach an image in the message composer. It is only possible in mail composer.

how to attach any document in email in iphone app

I am sending email from iphone app it is working fine but i want that with email i should attached a pdf file which is documents folder of the app.for testing first i attached a png from resources folder of app but it does not get attached and not sent in email i am using following code.
- (IBAction)onEmailResult
{
if ([[MFMailComposeViewController class] canSendMail]) {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Pig Game"];
[picker setToRecipients:toRecipients];
int a=10;
int b=100;
NSString *path = [[NSBundle mainBundle] pathForResource:#"project existing photo" ofType:#"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"png" fileName:#"icon.png"];
NSString * emailBody = [NSString stringWithFormat:#"My Score %d",a];
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release];
}
else {
int a=10;
int b=20;
NSString *recipients = #"mailto:imran_husain_2000#yahoo.com?&subject=Pig Game";
NSString *body = [NSString stringWithFormat:#"&body=My Score: %d/%d, My Time: %#", a,b, time];
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
}
Try following code snippet.
- (NSString *)pathForFile : (NSString *) fileName{
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: fileName];
}
- (void)sendMailWithAttachedFile:(NSString *) fileName extention:(NSString *) extension{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
// NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForResourse:fileName ofType:extension]];
NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForFile:[NSString stringWithFormat:#"%#.%#", fileName, extension]]];
NSData *data=[[NSData alloc]initWithContentsOfURL:outputURL];
[picker addAttachmentData:data mimeType:#"application/pdf" fileName:#"TestOne.pdf"];
[self presentViewController:picker animated:YES completion:nil];
}
Now Call Send Mail method As:
[self sendMailWithAttachedFile:#"TestOne" :#"pdf"];
-(void)displayMailComposerSheet
{
NSData *soundFile = [[NSData alloc] initWithContentsOfURL:YourDocumentFile];
[mail addAttachmentData:soundFile mimeType:#".txt" fileName:#"YourDocumentFile.txt"];
}
This code implement in displayMailComposerSheet i hope this code is useful for You
MFMailComposeViewController *picker1 = [[MFMailComposeViewController alloc] init];
NSArray *recipentsArray = [[NSArray alloc]initWithObjects:[shopDictValues objectForKey:#"vEmail"], nil];
picker1.mailComposeDelegate = self;
picker1.modalPresentationStyle = UIModalPresentationFormSheet;
[picker1 setSubject:#"Subject"];
[picker1 setToRecipients:recipentsArray];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableArray *arydefault = [[NSMutableArray alloc]initWithArray:[[NSUserDefaults standardUserDefaults] valueForKey:#"jacketCount"]];
for (int i=0;i<arydefault.count;i++)
{
NSString *pdfFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#%#.pdf",[[arydefault objectAtIndex:i]valueForKey:#"productlinename"],[arydefault objectAtIndex:i]]];
[picker1 addAttachmentData:[NSData dataWithContentsOfFile:pdfFilePath] mimeType:#"application/pdf" fileName:[NSString stringWithFormat:#"Order - %#",[[[NSString stringWithFormat:#"%#%i",[[arr objectAtIndex:i]valueForKey:#"productlinename"],i] componentsSeparatedByCharactersInSet: [[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:#""]]];
}
NSString *emailBody = #"Email Body goes here.";
[picker1 setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:picker1 animated:YES];

How to send a label's text as an email attachment?

I want to attach a label text to an email,
How can I send a text inside a UILabel as an attachment to email ?
This is the code I'm using :
-(IBAction)send:(id)sender {
if ([MFMailComposeViewController canSendMail])
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 100)];
label.numberOfLines = 0;
label.textAlignment = UITextAlignmentCenter;
label.text = #"text";
[self.view addSubview:label];
[label release];
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"Subject"];
NSString *fileName = #"my file.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *myData = [NSData dataWithContentsOfFile:path];
[mailer addAttachmentData:myData mimeType:#"text/plain" fileName:fileName];
// Fill out the email body text
NSString *emailBody = #"Email Body";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
[mailer release];
}
else
{
UIAlertView *alertm = [[UIAlertView alloc] initWithTitle:#"Failure"
message:#"Please make sure that your email application is open"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertm show];
[alertm release];
}
}
How can I link that label to attach it to email ?
Any help will be appreciated.
you're almost there.
-- you read text from a file and attach it
===
read the data not from the file but from the label itself
NSData *data = [self.label.text dataUsingEncoding:NSUTF8Encoding];
You can add the Label text to the Body.
NSString *emailBody = [NSString stringWithFormat:#"Your Voice File Attached. %#", label.text];
something like this

Data Attached in E-mail?

My NSMutableArray data are in NSData formate.I am trying to attached NSMutableArray data to E-mail body.Here is my NSMutableArray code:
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSString *msg1 = [defaults1 objectForKey:#"key5"];
NSData *colorData = [defaults1 objectForKey:#"key6"];
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
NSData *colorData1 = [defaults1 objectForKey:#"key7"];
UIColor *color1 = [NSKeyedUnarchiver unarchiveObjectWithData:colorData1];
NSData *colorData2 = [defaults1 objectForKey:#"key8"];
UIFont *color2 = [NSKeyedUnarchiver unarchiveObjectWithData:colorData2];
CGFloat x =(arc4random()%100)+100;
CGFloat y =(arc4random()%100)+250;
lbl = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 100, 70)];
lbl.userInteractionEnabled=YES;
lbl.text=msg1;
lbl.backgroundColor=color;
lbl.textColor=color1;
lbl.font =color2;
lbl.lineBreakMode = UILineBreakModeWordWrap;
lbl.numberOfLines = 50;
[self.view addSubview:lbl];
[viewArray addObject:lbl ];
viewArray is my NSMutableArray .All the data store in viewArray are in NSData formate.I try this code to attached viewArray data in E-mail.
- (IBAction)sendEmail {
if ([MFMailComposeViewController canSendMail])
{
NSArray *recipients = [NSArray arrayWithObject:#"example#yahoo.com"];
MFMailComposeViewController *controller = [[MFMailComposeViewController
alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"Iphone Game"];
NSLog(#"viewArray: %#", viewArray);
NSString *string = [viewArray componentsJoinedByString:#"\n"];
NSString *emailBody = string;
NSLog(#"test=%#",emailBody);
[controller setMessageBody:emailBody isHTML:YES];
[controller setToRecipients:recipients];
[self presentModalViewController:controller animated:YES];
[controller release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Your device is not set up for email." delegate:self
cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
Here i see objects store in viewArray.in console its look like this..[2012-05-07 18:48:00.065 Note List[279:207] test=UILabel: 0x8250850; frame = (140 341; 56 19); text = 'Xxxxxxx'; clipsToBounds = YES; layer = > but in E-mail i see only this..>> please suggest any one how can i attached my viewArray data in E-mail.
]
in email attachement, you can only send NSData or string to email, now if you want to send it by string, then get all values you want to send email like, lable.text, lable.color, lable.alpha etc, with proper keys and place it in the body and parse there, else find some way to convert your object into NSData and attach it using mfmailcomposer attach data method
read this to convert NSArray into NSData
How to convert NSArray to NSData?
and this to convert back the NSData to NSArray
How can i convert a NSData to NSArray?
and then write this data to file as,
-(void)writeDataToFile:(NSString*)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if(filename==nil)
{
DLog(#"FILE NAME IS NIL");
return;
}
// the path to write file
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"%#",filename]];
/*NSData *writeData;
writeData=[NSKeyedArchiver archivedDataWithRootObject:pArray]; */
NSFileManager *fm=[NSFileManager defaultManager];
if(!filePath)
{
//DLog(#"File %# doesn't exist, so we create it", filePath);
[fm createFileAtPath:filePath contents:self.mRespData attributes:nil];
}
else
{
//DLog(#"file exists");
[self.mRespData writeToFile:filePath atomically:YES];
}
NSMutableData *resData = [[NSMutableData alloc] init];
self.mRespData=resData;
[resData release];
}
and finally attach it to the email using
- (void)addAttachmentData:(NSData *)attachment mimeType:(NSString *)mimeType fileName:(NSString *)filename

Send an iphone attachment through email programmatically

I am writing an iPhone app that requires that I send an e-mail attachment programmatically. The attachment is a csv file, that I create through the code. I then attach the file to the email, and the attachment shows up on the phone. When I send the email to myself, however, the attachment doesn't appear in the e-mail. Here is the code I'm using.
[self exportData];
if ([MFMailComposeViewController canSendMail])
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"expenses" ofType:#"csv"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"Vehicle Expenses from myConsultant"];
NSString *emailBody = #"";
[mailer setMessageBody:emailBody isHTML:NO];
[mailer addAttachmentData:myData mimeType:#"text/plain" fileName:#"expenses"];
[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];
}
}
- (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];
The is being successfully created- I checked in the simulator files.
- (void) exportData
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *root = [documentsDir stringByAppendingPathComponent:#"expenses.csv"];
NSString *temp=#"Date,Purpose,Start Odometer,End Odometer, Total Driven, Fees, ";
for(int i = 0; i < expenses.count; i++){
VehicleExpense *tempExpense = [expenses objectAtIndex:i];
temp = [temp stringByAppendingString:tempExpense.date];
temp = [temp stringByAppendingString:#", "];
temp = [temp stringByAppendingString:tempExpense.purpose];
temp = [temp stringByAppendingString:#", "];
temp = [temp stringByAppendingString:[NSString stringWithFormat: #"%.02f",tempExpense.start_mile]];
temp = [temp stringByAppendingString:#", "];
temp = [temp stringByAppendingString:[NSString stringWithFormat: #"%.02f",tempExpense.end_mile]];
temp = [temp stringByAppendingString:#", "];
temp = [temp stringByAppendingString:[NSString stringWithFormat: #"%.02f",tempExpense.distance]];
temp = [temp stringByAppendingString:#", "];
temp = [temp stringByAppendingString:[NSString stringWithFormat: #"%.02f",tempExpense.fees]];
temp = [temp stringByAppendingString:#", "];
}
[temp writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"got here in export data--- %#", documentsDir);
}
try
[mailer addAttachmentData:myData mimeType:#"text/csv" fileName:#"expenses.csv"];
Edit:
This is the code I'm using in my app:
- (IBAction) ExportData:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:kExportFileName];
self.timeRecords = [[NSMutableArray alloc] init];
for (int i=0; i< [self.selectedTimeEntries count]; i++)
for (int j=0; j<[[self.selectedTimeEntries objectAtIndex:i] count]; j++)
if ([[self.selectedTimeEntries objectAtIndex:i] objectAtIndex:j] == [NSNumber numberWithBool:YES])
[self.timeRecords addObject:[self timeEntriesForDay:[self.uniqueArray objectAtIndex:i] forIndex:j]];
if( !([self.timeRecords count]!=0))
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"There are no time entries selected!" message:#"Please select at least one time entry before proceeding" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
NSMutableString *csvLine;
NSError *err = nil;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dateString = nil;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPositiveFormat:#"###0.##"];
NSString *formattedNumberString = nil;
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}
for (timeEntries *timeEntry in self.timeRecords) {
csvLine = [NSMutableString stringWithString:timeEntry.client];
[csvLine appendString:#","];
[csvLine appendString:timeEntry.category];
[csvLine appendString:#","];
[csvLine appendString:timeEntry.task];
[csvLine appendString:#","];
dateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeEntry.date]];
[csvLine appendString:dateString];
[csvLine appendString:#","];
formattedNumberString = [numberFormatter stringFromNumber:timeEntry.duration];
[csvLine appendString:formattedNumberString];
[csvLine appendString:#","];
[csvLine appendString:timeEntry.description];
[csvLine appendString:#"\n"];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSString *oldFile = [[NSString alloc] initWithContentsOfFile:filePath];
[csvLine insertString:oldFile atIndex:0];
BOOL success =[csvLine writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:&err];
if(success){
}
[oldFile release];
}
}
if (!appDelegate.shouldSendCSV) {
self.csvText = csvLine;
}
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
[self emailExport:filePath];
}
self.selectedTimeEntries =nil;
self.navigationController.toolbarHidden = NO;
}
- (void)emailExport:(NSString *)filePath
{
NSLog(#"Should send CSV = %#", [NSNumber numberWithBool:appDelegate.shouldSendCSV]);
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
// Set the subject of email
[picker setSubject:#"My Billed Time Export"];
// Add email addresses
// Notice three sections: "to" "cc" and "bcc"
NSString *valueForEmail = [[NSUserDefaults standardUserDefaults] stringForKey:#"emailEntry"];
NSString *valueForCCEmail = [[NSUserDefaults standardUserDefaults] stringForKey:#"ccEmailEntry"];
if( valueForEmail == nil || [valueForEmail isEqualToString:#""])
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Please set an email address before sending a time entry!" message:#"You can change this address later from the settings menu of the application!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
else {
[picker setToRecipients:[NSArray arrayWithObjects:valueForEmail, nil]];
}
if(valueForCCEmail != nil || ![valueForCCEmail isEqualToString:#""])
{
[picker setCcRecipients:[NSArray arrayWithObjects:valueForCCEmail, nil]];
}
// Fill out the email body text
NSString *emailBody = #"My Billed Time Export File.";
// This is not an HTML formatted email
[picker setMessageBody:emailBody isHTML:NO];
if (appDelegate.shouldSendCSV) {
// Create NSData object from file
NSData *exportFileData = [NSData dataWithContentsOfFile:filePath];
// Attach image data to the email
[picker addAttachmentData:exportFileData mimeType:#"text/csv" fileName:#"MyFile.csv"];
} else {
[picker setMessageBody:self.csvText isHTML:NO];
}
// Show email view
[self presentModalViewController:picker animated:YES];
// Release picker
[picker release];
}
Dani's answer is great, however the code seems to be too long for someone looking for a simple way to send an attachment through email programatically.
The Gist
I pruned his answer to take out only the important bits, as well as refactored it like so:
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
mailComposer.subject = #"Sample subject";
mailComposer.toRecipients = #[#"arthur#example.com", #"jeanne#example.com", ...];
mailComposer.ccRecipients = #[#"nero#example.com", #"mashu#example.com", ...];
[mailComposer setMessageBody:#"Sample body" isHTML:NO];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
[mailComposer addAttachmentData:fileData
mimeType:mimeType
fileName:fileName];
[self presentViewController:mailComposer animated:YES completion:nil];
That's basically the gist of it, this is enough as it is. If, for example, you put this code on a button's action, it will present an email composing screen with the respective fields pre-filled up, as well as having the file you want attached to the email.
Further Reading
Framework
The MFMailComposeViewController is under the MessageUI Framework, so to use it, import (if you have not done yet) the Framework like so:
#import <MessageUI/MessageUI.h>
Mail Capability Checking
Now when you run the source code, and you have not yet setup a mail account on your device, (not sure what the behavior is on simulator), this code will crash your app. It seems that if the mail account is not yet setup, doing [[MFMailComposeViewController alloc] init] will still result in the mailComposer being nil, causing the crash. As the answer in the linked question states:
You should check is MFMailComposeViewController are able to send your mail just before sending
You can do this by using the canSendMail method like so:
if (![MFMailComposeViewController canSendMail]) {
[self openCannotSendMailDialog];
return;
}
You can put this right before doing [[MFMailComposeViewController alloc] init] so that you can notify the user immediately.
Handling cannotSendMail
If canSendMail returns false, according to Apple Dev Docs, that means that the device is not configured for sending mail. This could mean that maybe the user has not yet setup their Mail account. To help the user with that, you can offer to open the Mail app and setup their account. You can do this like so:
NSURL *mailUrl = [NSURL URLWithString:#"message://"];
if ([[UIApplication sharedApplication] canOpenURL:mailUrl]) {
[[UIApplication sharedApplication] openURL:mailUrl];
}
You can then implement openCannotSendMailDialog like so:
- (void)openCannotSendMailDialog
{
UIAlertController *alert =
[UIAlertController alertControllerWithTitle:#"Error"
message:#"Cannot send mail."
preferredStyle:UIAlertControllerStyleAlert];
NSURL *mailUrl = [NSURL URLWithString:#"message://"];
if ([[UIApplication sharedApplication] canOpenURL:mailUrl]) {
[alert addAction:
[UIAlertAction actionWithTitle:#"Open Mail"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
[[UIApplication sharedApplication] openURL:mailUrl];
}]];
[alert addAction:
[UIAlertAction actionWithTitle:#"Cancel"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * _Nonnull action) {
}]];
} else {
[alert addAction:
[UIAlertAction actionWithTitle:#"OK"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * _Nonnull action) {
}]];
}
[self presentViewController:alert animated:YES completion:nil];
}
Mime Types
If like me, you forgot/are unsure which mimeType to use, here is a resource you can use. Most probably, text/plain is enough, if the file you are attaching is just a plain text, or image/jpeg / image/png for images.
Delegate
As you probably noticed, Xcode throws us a warning on the following line:
mailComposer.mailComposeDelegate = self;
This is because we have not yet set ourself to conform to the appropriate protocol and implement its delegate method. If you want to receive events whether the mail was cancelled, saved, sent or even failed sending, you need to set your class to conform to the protocol MFMailComposeViewControllerDelegate, and handle the following events:
MFMailComposeResultSent
MFMailComposeResultSaved
MFMailComposeResultCancelled
MFMailComposeResultFailed
According to Apple Dev Docs (emphasis mine):
The mail compose view controller is not dismissed automatically. When the user taps the buttons to send the email or cancel the interface, the mail compose view controller calls the mailComposeController:didFinishWithResult:error: method of its delegate. Your implementation of that method must dismiss the view controller explicitly.
With this in mind, we can then implement the delegate method like so:
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
switch (result) {
case MFMailComposeResultSent:
// Mail was sent
break;
case MFMailComposeResultSaved:
// Mail was saved as draft
break;
case MFMailComposeResultCancelled:
// Mail composition was cancelled
break;
case MFMailComposeResultFailed:
//
break;
default:
//
break;
}
// Dismiss the mail compose view controller.
[controller dismissViewControllerAnimated:YES completion:nil];
}
Conclusion
The final code may look like so:
- (void)openMailComposerWithSubject:(NSString *)subject
toRecipientArray:(NSArray *)toRecipientArray
ccRecipientArray:(NSArray *)ccRecipientArray
messageBody:(NSString *)messageBody
isMessageBodyHTML:(BOOL)isHTML
attachingFileOnPath:(NSString)filePath
mimeType:(NSString *)mimeType
{
if (![MFMailComposeViewController canSendMail]) {
[self openCannotSendMailDialog];
return;
}
MFMailComposeViewController *mailComposer =
[[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
mailComposer.subject = subject;
mailComposer.toRecipients = toRecipientArray;
mailComposer.ccRecipients = ccRecipientArray;
[mailComposer setMessageBody:messageBody isHTML:isHTML];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSString *fileName = filePath.lastPathComponent;
[mailComposer addAttachmentData:fileData
mimeType:mimeType
fileName:fileName];
[self presentViewController:mailComposer animated:YES completion:nil];
}
- (void)openCannotSendMailDialog
{
UIAlertController *alert =
[UIAlertController alertControllerWithTitle:#"Error"
message:#"Cannot send mail."
preferredStyle:UIAlertControllerStyleAlert];
NSURL *mailUrl = [NSURL URLWithString:#"message://"];
if ([[UIApplication sharedApplication] canOpenURL:mailUrl]) {
[alert addAction:
[UIAlertAction actionWithTitle:#"Open Mail"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
[[UIApplication sharedApplication] openURL:mailUrl];
}]];
[alert addAction:
[UIAlertAction actionWithTitle:#"Cancel"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * _Nonnull action) {
}]];
} else {
[alert addAction:
[UIAlertAction actionWithTitle:#"OK"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * _Nonnull action) {
}]];
}
[self presentViewController:alert animated:YES completion:nil];
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
NSString *message;
switch (result) {
case MFMailComposeResultSent:
message = #"Mail was sent.";
break;
case MFMailComposeResultSaved:
message = #"Mail was saved as draft.";
break;
case MFMailComposeResultCancelled:
message = #"Mail composition was cancelled.";
break;
case MFMailComposeResultFailed:
message = #"Mail sending failed.";
break;
default:
//
break;
}
// Dismiss the mail compose view controller.
[controller dismissViewControllerAnimated:YES completion:^{
if (message) {
UIAlertController *alert =
[UIAlertController alertControllerWithTitle:#"Confirmation"
message:message
preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:
[UIAlertAction actionWithTitle:#"OK"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
With the button action looking like:
- (IBAction)mailButtonTapped:(id)sender
{
NSString *reportFilePath = ...
[self openMailComposerWithSubject:#"Report Files"
toRecipientArray:mainReportRecipientArray
ccRecipientArray:subReportRecipientArray
messageBody:#"I have attached report files in this email"
isMessageBodyHTML:NO
attachingFileOnPath:reportFilePath
mimeType:#"text/plain"];
}
I kind of went overboard here, but you can, with a grain of salt, take and use the code I posted here. Of course there is a need to adapt it to your requirements, but that is up to you. (I also modified this answer from my working source code, so there might be errors somewhere, please do comment if you find one :))
The issue was that I wasn't looking in the proper place for the file. Thanks #EmilioPalesz .
Here's the code I needed:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *root = [documentsDir stringByAppendingPathComponent:#"expenses.csv"]
NSData *myData = [NSData dataWithContentsOfFile:root];