How to send an attachment in email using Swift?


To send an email from our iPhone device using our application we need to import the MessageUI framework of iOS SDK. After importing the framework in your application, drag and drop a button on the view controller. Add empty action for that button.

Now add the following code in your view controller.

funccomposeEmail(to email: String,subject: String,Body: String) {
   if( MFMailComposeViewController.canSendMail()) {
      letmailComposer = MFMailComposeViewController()
      mailComposer.mailComposeDelegate = self
      mailComposer.setToRecipients([email])
      mailComposer.setSubject(subject)
      mailComposer.setMessageBody(Body, isHTML: true)
      letpathPDF = "\(NSTemporaryDirectory())result.pdf"
      if let fileData = NSData(contentsOfFile: pathPDF) {
         mailComposer.addAttachmentData(fileData as Data, mimeType: "application/pdf", fileName: "result.pdf")
      }
      self.present(mailComposer, animated: true, completion: nil)
      } else {
         print("email is not supported")
      }
   }
   funcmailComposeController(_ didFinishWithcontroller:
   MFMailComposeViewController, didFinishWith result:
   MFMailComposeResult, error: Error?) {
      self.dismiss(animated: true, completion: nil)
   }
}

Call this method inside the action of a button you just created.

@IBActionfuncactionButtonOne(_ sender: Any) {
composeEmail(to: "ashish@xy.com", subject: "Saying Hi", Body: "Hey there, hope you are doing well.")
}

When we run the above code and press the button we added, we get the following result.

There are some points to be noted −

  • Make sure that at least one account is added in the mail application on your iPhone.

  • Make sure you have the pdf stored locally on the address, which you want to upload.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jun-2020

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements