Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach a PDF file to email - Swift

I want to send email with a PDF attachment. I created PDF file, then I did the following which is wrong I believe:

// locate folder containing pdf file            
let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String

let pdfFileName = documentsPath.stringByAppendingPathComponent("chart.pdf")
let fileData = NSData(contentsOfFile: pdfFileName)
mc.addAttachmentData(fileData, mimeType: "pdf", fileName: chart)

Before sending the email, I can see attached chart.pdf, but when I sent the email, it was sent without attachment and this is because I didn't attached correctly the file.

like image 338
Xin Lok Avatar asked May 24 '15 12:05

Xin Lok


2 Answers

we can attache PDF file with email and send it programmatically

with Swift 2.2

@IBAction func sendEmail(sender: UIButton)
    {
        //Check to see the device can send email.
        if( MFMailComposeViewController.canSendMail() )
        {
            print("Can send email.")

            let mailComposer = MFMailComposeViewController()
            mailComposer.mailComposeDelegate = self

            //Set to recipients
            mailComposer.setToRecipients(["your email address heres"])

            //Set the subject
            mailComposer.setSubject("email with document pdf")

            //set mail body
            mailComposer.setMessageBody("This is what they sound like.", isHTML: true)

            if let filePath = NSBundle.mainBundle().pathForResource("All_about_tax", ofType: "pdf")
            {
                print("File path loaded.")

                if let fileData = NSData(contentsOfFile: filePath)
                {
                    print("File data loaded.")
                    mailComposer.addAttachmentData(fileData, mimeType: "application/pdf", fileName: "All_about_tax.pdf")

                }
            }

            //this will compose and present mail to user
            self.presentViewController(mailComposer, animated: true, completion: nil)
        }
        else
        {
            print("email is not supported")
        }
    }

    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
like image 146
swiftBoy Avatar answered Nov 15 '22 14:11

swiftBoy


You are passing wrong mimeType to addAttachmentData(). Use application/pdf instead of pdf.

like image 22
NightFury Avatar answered Nov 15 '22 14:11

NightFury