6

I have been pulling my hair out lately trying to create a .txt file into an email.

I have a variable which is a list of strings that I want to write to a txt file, and then add as an attachment to an email.

I have not been able to find any decent documentation on this.

Looking forward to some great input. Thank you!

Edit---------- I found this code sample: and I am getting the following error.

@IBAction func createFile(sender: AnyObject) {
        let path = tmpDir.stringByAppendingPathComponent(fileName)
        let contentsOfFile = "Sample Text"
        var error: NSError?

        // Write File
        if contentsOfFile.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error) == false {
            if let errorMessage = error {
                println("Failed to create file")
                println("\(errorMessage)")
            }
        } else {
            println("File sample.txt created at tmp directory")
        }
    }

let path = tmpDir.stringByAppendingPathComponent(fileName)

I am getting an error telling me "Value of type 'String' has no member URLByAppendingPathComponent' "

How do I fix that?

Lorenzo
  • 3,293
  • 4
  • 29
  • 56
Danny06191
  • 133
  • 1
  • 9

1 Answers1

19

For sending mail with attachment

import MessageUI


@IBAction func sendEmail(sender: UIButton) {

    if( MFMailComposeViewController.canSendMail() ) {
let mailComposer = MFMailComposeViewController()
            mailComposer.mailComposeDelegate = self

            //Set the subject and message of the email
            mailComposer.setSubject("Subject")
            mailComposer.setMessageBody("body text", isHTML: false)

            if let fileData = NSData(contentsOfFile: filePath) {
                mailComposer.addAttachmentData(fileData, mimeType: "text/txt", fileName: "data")
            }

            self.presentViewController(mailComposer, animated: true, completion: nil)
    }
}

based on http://kellyegan.net/sending-files-using-swift/

Create the file from array

let strings = ["a","b"]
let joinedString = strings.joinWithSeparator("\n")
do {
    try joinedString.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
} catch {

}

You can however create the NSData from the string instead of first writing it to file.

//example data
let filename = "testfile"
let strings = ["a","b"]

if(MFMailComposeViewController.canSendMail()){

    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self
    mailComposer.setToRecipients([mail])
    mailComposer.setSubject("\(subject)" )
    mailComposer.setMessageBody("\(messagebody)", isHTML: false)

    let joinedString = strings.joinWithSeparator("\n")
    print(joinedString)
    if let data = (joinedString as NSString).dataUsingEncoding(NSUTF8StringEncoding){
        //Attach File
        mailComposer.addAttachmentData(data, mimeType: "text/plain", fileName: "test")
        self.presentViewController(mailComposer, animated: true, completion: nil)
    }
}

And then dismiss the composer controller on a result

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    controller.dismissViewControllerAnimated(true, completion: nil)
}
Moriya
  • 7,750
  • 3
  • 35
  • 53
  • Animal. Thanks for replying man. I have this current code http://pastebin.com/wH10RLup it does not show an attachment at all, and I don't think I missed anything. Please take a look. Thanks! Also, the variable I have is already joined with \n lines. – Danny06191 Oct 27 '15 at 04:04
  • Unfortunately, it isn't. No errors. But nothing attaches. – Danny06191 Oct 27 '15 at 04:24
  • I updated the answer above a little bit but I have to do a lot of work to really test this. Can you check the value of 'data' and see that it has been written too? – Moriya Oct 27 '15 at 04:52
  • I just wanted to know where in the execution you are having problems. Can you set a breakpoint after the data variable is giver a value and check if it really gets any data from the string? – Moriya Oct 27 '15 at 05:00
  • i tried to print data and it isn't getting anything. – Danny06191 Oct 27 '15 at 05:01
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/93437/discussion-between-animal-and-user2913654). – Moriya Oct 27 '15 at 05:02
  • This is the correct answer. He is indeed, an Animal! – Danny06191 Oct 27 '15 at 06:00
  • This got me so close... Note: the optional method for dismissing as changed! It is now, "func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?)" The small change is, "didFinishWith" vs "didFinishWithResult" Took me forever to figure this out.. Hope this saves someone else. Otherwise, this answer is spot on! – CD-3 Sep 28 '21 at 21:57