You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MFMailComposeViewController为邮件附加相册选中图片的问题

功能实现需求

实现用户从系统相册选择目标图片后,自动将选中图片附加到待发送邮件的功能。
当前已完成进度:

  • 相册唤起按钮开发完成,用户点击可打开系统相册
  • 选中图片后可正常展示在名为imageView的UIImageView控件中
  • 现存问题:addAttachment附件添加逻辑存在错误,无法正确附加选中图片

现有代码

打开相册按钮实现代码

@IBAction func openPhotoLibraryButton(sender: AnyObject) {
    if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary;
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true, completion: nil)
    }
}

邮件发送功能现有代码

@IBAction func sendEmail(_ sender: Any) {
    if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        let emailFullName: String = fullName.text!
        let emailCell: String = cellNumber.text!
        let image1: UIImage = imageView.image!
        mail.mailComposeDelegate = self
        // 收件人
        mail.setToRecipients(["kondja99@gmail.com"])
        // 邮件正文
        mail.setMessageBody("FullName: \(emailFullName) \n Cellphone No: \(emailCell)"   , isHTML: false)
        // 邮件主题
        mail.setSubject("Application for RTO: ")
        
        // 邮件附件(错误代码段)
        mail.addAttachmentData(Data, mimeType: "image/jpg", fileName: "\(image1)")
        self.present(mail, animated: true, completion: nil)
        }
     else {
        print("Email cannot be sent")
        
    }
}

错误原因

原附件添加代码存在两处核心问题:

  1. 第一个参数直接传入了Data类型本身,没有传入从选中图片转换得到的实际二进制数据
  2. 文件名参数直接将UIImage实例做字符串插值,得到的是图片对象的内存地址字符串(格式类似<UIImage: 0x600000xxxxxx>),不是合法的图片文件名,会导致附件识别异常

修正方案
  1. 先将imageView中的图片转换为JPEG格式的二进制数据,增加空判断避免强制解包导致的崩溃
  2. 设置合法的带后缀的附件文件名,使用标准MIME类型
  3. 将转换得到的图片二进制数据传入附件添加方法

修正后的完整邮件发送代码如下:

@IBAction func sendEmail(_ sender: Any) {
    guard MFMailComposeViewController.canSendMail() else {
        print("Email cannot be sent")
        return
    }
    
    let mail = MFMailComposeViewController()
    let emailFullName: String = fullName.text ?? ""
    let emailCell: String = cellNumber.text ?? ""
    mail.mailComposeDelegate = self
    
    // 收件人
    mail.setToRecipients(["kondja99@gmail.com"])
    // 邮件正文
    mail.setMessageBody("FullName: \(emailFullName) \n Cellphone No: \(emailCell)", isHTML: false)
    // 邮件主题
    mail.setSubject("Application for RTO: ")
    
    // 修正后的附件添加逻辑
    if let selectedImage = imageView.image, let imageData = selectedImage.jpegData(compressionQuality: 0.8) {
        // compressionQuality取值范围0~1,数值越高画质越好、文件越大
        mail.addAttachmentData(imageData, mimeType: "image/jpeg", fileName: "application_photo.jpg")
    }
    
    self.present(mail, animated: true, completion: nil)
}

内容的提问来源于stack exchange,提问作者Sindano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 14:39:07