[iOS] Create Email with Attachment

iOS 寄信範本:

(void)showEmail:(NSString*)file {
    NSString *emailTitle = @”Great Photo and Doc”;
    NSString *messageBody = @”Hey, check this out!”;
    NSArray *toRecipents = [NSArray arrayWithObject:@”[email protected]];
    
    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;
    [mc setSubject:emailTitle];
    [mc setMessageBody:messageBody isHTML:NO];
    [mc setToRecipients:toRecipents];
    
    // Determine the file name and extension
    NSArray *filepart = [file componentsSeparatedByString:@”.”];
    NSString *filename = [filepart objectAtIndex:0];
    NSString *extension = [filepart objectAtIndex:1];
    
    // Get the resource path and read the file using NSData
    NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    
    // Determine the MIME type
    NSString *mimeType;
    if ([extension isEqualToString:@”jpg”]) {
        mimeType = @”image/jpeg”;
    } else if ([extension isEqualToString:@”png”]) {
        mimeType = @”image/png”;
    } else if ([extension isEqualToString:@”doc”]) {
        mimeType = @”application/msword”;
    } else if ([extension isEqualToString:@”ppt”]) {
        mimeType = @”application/vnd.ms-powerpoint”;
    } else if ([extension isEqualToString:@”html”]) {
        mimeType = @”text/html”;
    } else if ([extension isEqualToString:@”pdf”]) {
        mimeType = @”application/pdf”;
    }
    
    // Add attachment
    [mc addAttachmentData:fileData mimeType:mimeType fileName:filename];
    
    // Present mail view controller on screen
    [self presentViewController:mc animated:YES completion:NULL];
    
}
(void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@”Mail cancelled”);
            break;
        case MFMailComposeResultSaved:
            NSLog(@”Mail saved”);
            break;
        case MFMailComposeResultSent:
            NSLog(@”Mail sent”);
            break;
        case MFMailComposeResultFailed:
            NSLog(@”Mail sent failure: %@”, [error localizedDescription]);
            break;
        default:
            break;
    }
    
    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];
}

 

from:

iOS Programming 101: How To Create Email with Attachment

or:

    // we are cycling the damned GlobalMailComposer… due to horrible iOS issue

    // http://stackoverflow.com/questions/25604552/i-have-real-misunderstanding-with-mfmailcomposeviewcontroller-in-swift-ios8-in/25864182#25864182

相關文章

寫留言

你的電子郵件位址並不會被公開。 必要欄位標記為 *