10

Tôi có một tập tin .txt lưu trữ trong thư mục Documents và tôi muốn gửi nó bằng cách MFMailComposeViewController với mã tiếp theo trong cơ thể của -sendEmail phương pháp:Gắn .txt để MFMailComposeViewController

NSData *txtData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dataBase" ofType:@"txt"]]; 
     [mail addAttachmentData:txtData mimeType:@"text/plain" fileName:[NSString stringWithFormat:@"dataBase.txt"]]; 

Khi Thư nhà soạn nhạc dường như tôi có thể nhìn thấy tệp đính kèm trong phần thân thư nhưng tôi nhận được thư này mà không có tệp đính kèm. Có thể nó sai MIME-type cho tập tin đính kèm .txt hoặc một cái gì đó sai với mã này?

Cảm ơn

Trả lời

25
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0];   
     NSString *txtFilePath = [documentsDirectory stringByAppendingPathComponent:@"abc.txt"]; 
NSData *noteData = [NSData dataWithContentsOfFile:txtFilePath]; 
     MFMailComposeViewController *_mailController = [[MFMailComposeViewController alloc] init]; 
     [_mailController setSubject:[NSString stringWithFormat:@"ABC"]]; 
     [_mailController setMessageBody:_messageBody 
           isHTML:NO]; 
     [_mailController setMailComposeDelegate:self]; 
     [_mailController addAttachmentData:noteData mimeType:@"text/plain" fileName:@"abc.txt"]; 

Hy vọng nó giúp.

+0

Cảm ơn bạn, đồng nghiệp! – Alex

+0

@Alexey Niềm vui của tôi :-) –

3

Trong Swift 3, bạn có thể gửi mail với file đính kèm như thế này

@IBAction func emailLogs(_ sender: Any) { 
    let allPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) 
    let documentsDirectory = allPaths.first! 
    let pathForLog = documentsDirectory.appending("/application.log") 

    if MFMailComposeViewController.canSendMail() { 
     let mail = MFMailComposeViewController() 
     mail.mailComposeDelegate = self; 
     mail.setToRecipients(["[email protected]"]) 
     mail.setSubject("Application Logs") 
     mail.setMessageBody("Please see attached", isHTML: true) 

     if let fileData = NSData(contentsOfFile: pathForLog) { 
      mail.addAttachmentData(fileData as Data, mimeType: "text/txt", fileName: "application.log") 
     } 

     self.present(mail, animated: true, completion: nil) 
    } 
} 

Và sau đó bỏ bộ điều khiển nhà soạn nhạc vào một kết quả

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { 
    controller.dismiss(animated: true, completion: nil) 
} 

Hãy chắc chắn để đăng ký đại biểu này

MFMailComposeViewControllerDelegate 
Các vấn đề liên quan