Attaching .txt to MFMailComposeViewController
Asked Answered
D

2

16

I have a .txt file stored in Documents Folder and I want to send it by MFMailComposeViewController with next code in the body of -sendEmail method:

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

When Mail composer appears I can see attachment in the mail body but I receive this mail without attachment. Maybe it is wrong MIME-type for .txt attachment or something wrong with this code?

Thanks

Dremadremann answered 5/2, 2013 at 12:32 Comment(0)
H
33
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"];

Hope it helps.

Heterophony answered 5/2, 2013 at 12:37 Comment(0)
D
11

In Swift 3, you can send mail with attachment like this

@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)
    }
}

And then dismiss the composer controller on a result

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

Make sure to subscribe to this delegate

MFMailComposeViewControllerDelegate
Detrital answered 11/5, 2017 at 5:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.