从您的应用程序发送一封附有图像的电子邮件 Swift

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

我已经尝试了很多关于在您的应用程序中发送电子邮件的教程,但是 none 我看过的教程展示了如何使用它发送图像。我正在从 .WriteToFile 恢复图像,该图像设置为 UIImageView。我应该如何发送带有照片的电子邮件?

尼尔

您需要在您的邮件中添加一个 attachmentData,对您的图片进行编码 在一个 NSData 中。这是一个示例,向您展示如何发送电子邮件 你的形象。我假设您有一个 UIViewController 可以在其中放置函数 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)
    }
  } 

}

为了关闭 VC,请在您的 ViewController 中包含以下方法:

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

此方法的文档在 MFMailComposeViewControllerDelegate 中报告。