Send a file as attachment in objective c

前端 未结 1 1499
庸人自扰
庸人自扰 2020-11-29 19:11

I want to mail a file (image) as an attachment by just picking it from an Image Picker. What is the appropriate way I can attach and mail a file (specifically, an image) in

相关标签:
1条回答
  • 2020-11-29 19:49

    Use the method below

    -(void)displayComposerSheet 
    {
        MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
        picker.mailComposeDelegate = self;
        [picker setSubject:@"Check out this image!"];
    
        // Set up recipients
        // NSArray *toRecipients = [NSArray arrayWithObject:@"first@example.com"]; 
        // NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil]; 
        // NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"]; 
    
        // [picker setToRecipients:toRecipients];
        // [picker setCcRecipients:ccRecipients];   
        // [picker setBccRecipients:bccRecipients];
    
        // Attach an image to the email
        UIImage *coolImage = ...;
        NSData *myData = UIImagePNGRepresentation(coolImage);
        [picker addAttachmentData:myData mimeType:@"image/png" fileName:@"coolImage.png"];
    
        // Fill out the email body text
        NSString *emailBody = @"My cool image is attached";
        [picker setMessageBody:emailBody isHTML:NO];
        [self presentModalViewController:picker animated:YES];
    
        [picker release];
    }
    

    And implement the delegate method

    - (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
    {   
        // Notifies users about errors associated with the interface
        switch (result)
        {
            case MFMailComposeResultCancelled:
                NSLog(@"Result: canceled");
                break;
            case MFMailComposeResultSaved:
                NSLog(@"Result: saved");
                break;
            case MFMailComposeResultSent:
                NSLog(@"Result: sent");
                break;
            case MFMailComposeResultFailed:
                NSLog(@"Result: failed");
                break;
            default:
                NSLog(@"Result: not sent");
                break;
        }
        [self dismissModalViewControllerAnimated:YES];
    }
    

    And in your interface file

    #import <MessageUI/MFMailComposeViewController.h>
    ...
    
    @interface ... : ... <MFMailComposeViewControllerDelegate>
    
    0 讨论(0)
提交回复
热议问题