First, import:
import MessageUI
And implement an email delegate for example
public class MyViewController : UIViewController, MFMailComposeViewControllerDelegate { ...
If you have a file or 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 compose :
public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?){ self.dismiss(animated: true, completion: nil) print("sent!") }
source share