首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS MFMailComposeViewController 添加多張圖片附件的正確代碼

     編輯:程式設計綜合問答

標準代碼


#import 

- (void)sendEmailWithImages:(NSArray *)images {
    if (![MFMailComposeViewController canSendMail]) {
        NSLog(@"設備未配置郵件賬戶");
        return;
    }

    MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
    mailVC.mailComposeDelegate = self;
    [mailVC setSubject:@"主題"];
    [mailVC setMessageBody:@"正文內容", isHTML:NO];

    for (int i = 0; i < images.count; i++) {
        UIImage *image = images[i];
        NSData *imageData = UIImageJPEGRepresentation(image, 0.8); // 或 UIImagePNGRepresentation
        NSString *fileName = [NSString stringWithFormat:@"image_%d.jpg", i];
        [mailVC addAttachmentData:imageData mimeType:@"image/jpeg" fileName:fileName];
    }

    [self presentViewController:mailVC animated:YES completion:nil];
}

// Delegate
- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error {
    [controller dismissViewControllerAnimated:YES completion:nil];
}

關鍵點

  1. MFMailComposeViewController 需導入 MessageUI.framework 並遵循 MFMailComposeViewControllerDelegate。
  2. canSendMail 必須檢查,模擬器/無郵件賬戶設備返回 NO。
  3. addAttachmentData:mimeType:fileName: 可多次調用,**每次添加一個附件**,循環遍歷圖片數組即可。
  4. 圖片轉 Data:UIImageJPEGRepresentation(image, 壓縮質量 0.0-1.0) 或 UIImagePNGRepresentation。
  5. 文件名建議帶索引避免衝突,MIME 類型與格式對應(jpeg/jpg → image/jpeg,png → image/png)。

Swift 版本


import MessageUI

func sendEmail(with images: [UIImage]) {
    guard MFMailComposeViewController.canSendMail() else { return }

    let mailVC = MFMailComposeViewController()
    mailVC.mailComposeDelegate = self
    mailVC.setSubject("主題")
    mailVC.setMessageBody("正文", isHTML: false)

    for (index, image) in images.enumerated() {
        if let data = image.jpegData(compressionQuality: 0.8) {
            mailVC.addAttachmentData(data, mimeType: "image/jpeg", fileName: "image_\(index).jpg")
        }
    }
    present(mailVC, animated: true)
}

func mailComposeController(_ controller: MFMailComposeViewController,
                           didFinishWith result: MFMailComposeResult,
                           error: Error?) {
    controller.dismiss(animated: true)
}

進階:添加網頁內容 (HTML) 作為正文


NSString *htmlBody = @"

標題

包含圖片:

"; [mailVC setMessageBody:htmlBody isHTML:YES]; // 注意:CID 內嵌圖片需特殊處理,MFMailComposeViewController 不直接支援, // 建議改用附件形式或第三方郵件庫 (如 MailCore2)。

總結

MFMailComposeViewController 循環調用 addAttachmentData:mimeType:fileName: 即可添加多張圖片附件。務必檢查 canSendMail、正確轉換圖片 Data、設置代理處理發送結果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved