Attach a PDF file to email - Swift
Asked Answered
A

3

11

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.

Advertence answered 24/5, 2015 at 12:39 Comment(0)
R
13

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

Rabato answered 24/5, 2015 at 12:46 Comment(4)
Thanks for your quick reply, i change to : mc.addAttachmentData(fileData, mimeType: "application/pdf", fileName: pdfFileName), but still email is sent without attachment.Advertence
Are you sure that fileData is not nil? and pdf is actually present on that path?Rabato
you are right, fileData was nil, then i had to change the "documentsPath" in let fileData = NSData(contentsOfFile: documentsPath) to "pdfFileName". now it is working very well. thank you very muchAdvertence
Glad to help you out :)Rabato
C
5

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)
    }
Chinaman answered 1/7, 2016 at 14:16 Comment(1)
I have an error: Use of undeclared type MFMailComposeViewController and MFMailComposeResultAviate
H
3

First one, import:

import MessageUI

And implement de Email Delegate, like

public class MyViewController : UIViewController, MFMailComposeViewControllerDelegate { ...

If you have the file or the Data type, you can use this function:

let filePath = NSBundle.mainBundle().pathForResource("chart", ofType: "pdf")
let fileData = NSData(contentsOfFile: filePath)
sendEmail(data:fileData)

Swift 4

func sendEmail(data:Data?){
    if( MFMailComposeViewController.canSendMail() ) {
        let mailComposer = MFMailComposeViewController()
        mailComposer.mailComposeDelegate = self

        mailComposer.setToRecipients(["[email protected]", "[email protected]", "[email protected]"])
        mailComposer.setSubject("Cotización")
        mailComposer.setMessageBody("My body message", isHTML: true)

        if let fileData = data {
            mailComposer.addAttachmentData(fileData, mimeType: "application/pdf", fileName: "MyFileName.pdf")
       }


       self.present(mailComposer, animated: true, completion: nil)
            return
    }
    print("Email is not configured")

}

And the compose:

public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?){
        self.dismiss(animated: true, completion: nil)
        print("sent!")
    }
Heat answered 26/7, 2018 at 23:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.