Attach a PDF file to email - Swift

后端 未结 3 1734
终归单人心
终归单人心 2020-12-08 23:34

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               


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 00:13

    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(["john@stackoverflow.com", "mrmins@mydomain.com", "anotheremail@email.com"])
            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!")
        }
    

提交回复
热议问题