Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send an iphone attachment through email programmatically

Tags:

email

iphone

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);

}
like image 580
coder Avatar asked Oct 19 '11 16:10

coder


People also ask

How do I email large attachments from my iPhone?

With Mail Drop, you can send attachments up to 5 GB in size. You can send these attachments right from Mail on your Mac, the Mail app on your iPhone, iPad, or iPod touch, and from iCloud.com on your Mac or PC. All files types are supported and attachments don't count against your iCloud storage.


1 Answers

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];
}
like image 87
Danut Pralea Avatar answered Nov 04 '22 16:11

Danut Pralea