将PDF文件附加到电子邮件 – Swift
我想发送带有PDF附件的电子邮件。 我创建了PDF文件,然后我做了以下哪些错误我相信:
// 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)
在发送电子邮件之前,我可以看到附带的chart.pdf
,但是当我发送电子邮件时,它是在没有附件的情况下发送的,这是因为我没有正确附加文件。
您将错误的mimeType
传递给addAttachmentData()
。 使用application/pdf
而不是pdf
。
我们可以用电子邮件附上PDF文件并以编程方式发送
使用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) }
第一个,导入:
import MessageUI
并实现de Email Delegate,就像
public class MyViewController : UIViewController, MFMailComposeViewControllerDelegate { ...
如果您有文件或Data
类型,则可以使用此function:
let filePath = NSBundle.mainBundle().pathForResource("chart", ofType: "pdf") let fileData = NSData(contentsOfFile: filePath) sendEmail(data:fileData)
斯威夫特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") }
并compose
:
public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?){ self.dismiss(animated: true, completion: nil) print("sent!") }