Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending an email from your app with an image attached in Swift

I've tried a lot of tutorials on sending emails in your app but none of the ones I've seen show how to send an image with it. I'm recovering an image from .WriteToFile, This image is set to a UIImageView. How should I send an email with my picture?

Niall

like image 446
Niall Kehoe Avatar asked Jul 14 '16 13:07

Niall Kehoe


People also ask

Is it possible to send an email with image as an attachment?

Position your cursor where you want the image in your message. Select Insert > Pictures. Browse your computer or online file locations for the picture you want to insert. Select the picture, then select Insert.

How do I add an attachment in Swift?

SWIFT displays the Document Management page. Go to the bottom it the page and select the Add Attachments/Related Documents link. The Attachments and Related Documents page enables you to add either an attachment or related document to an existing contract document.


1 Answers

You need to add an attachmentData to your mail, encoding your image in an NSData. This is an example that show you how to send an email with your image. I'm suppose that you have a UIViewController where you can put the function sendMail.

import MessageUI
class MyViewController: UIViewController, MFMailComposeViewControllerDelegate
{
  // .... your stuff

  func sendMail(imageView: UIImageView) {
    if MFMailComposeViewController.canSendMail() {
      let mail = MFMailComposeViewController()
      mail.mailComposeDelegate = self;
      mail.setCcRecipients(["[email protected]"])
      mail.setSubject("Your messagge")
      mail.setMessageBody("Message body", isHTML: false)
      let imageData: NSData = UIImagePNGRepresentation(imageView.image)!
      mail.addAttachmentData(imageData, mimeType: "image/png", fileName: "imageName.png")
      self.presentViewController(mail, animated: true, completion: nil)
    }
  } 

}

In order to dismiss the VC, include the following method in your ViewController:

func mailComposeController(controller: MFMailComposeViewController,
    didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        controller.dismissViewControllerAnimated(true, completion: nil)
}

The documentation for this method is reported in MFMailComposeViewControllerDelegate.

like image 159
Adda_25 Avatar answered Oct 09 '22 20:10

Adda_25