How to send an image via email (Swift snippet)

This is how I did it in Sigma app with Swift 3.0.

First you import MessageUI. Then you declare that your class adopts MFMailComposeViewControllerDelegate protocol. Then implement these two methods.

    @IBAction func shareViaEmail(_ sender: AnyObject) {
        
        if(image == nil){return}   
     
        let picker = MFMailComposeViewController()
        picker.setSubject("")
        
        let fileName = Date().stringFromDate(format:"yyyyddMMHHmmss") //My own method. Just put some name here
        
        picker.addAttachmentData(UIImageJPEGRepresentation(image!, CGFloat(1.0))!, mimeType: "image/jpeg", fileName:  "\(fileName).jpeg")
        picker.setMessageBody("", isHTML: false)
     
        picker.mailComposeDelegate = self
        

       present(picker, animated: true, completion: nil)
    
    }
    


    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        
        if(result == .sent){
            
            //you can log an event to your analytics service here
            
        }
        
        dismiss(animated: true, completion: nil)
    }

 

Leave a Reply

Your email address will not be published. Required fields are marked *