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

好久不见. 提交于 2020-06-11 04:26:18

问题


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


回答1:


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(["yyyy@xxx.com"])
      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.



来源:https://stackoverflow.com/questions/38375385/sending-an-email-from-your-app-with-an-image-attached-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!