Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách gửi email có đính kèm file (attachment) bằng Swift

Để gửi email kèm file đính kèm từ app iOS, dùng MFMailComposeViewController từ framework MessageUI. Cách này mở giao diện soạn mail trong app (modal), cho phép đính kèm file, HTML body.

1. Import MessageUI & Conform Delegate


import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
    // ...
}

2. Hàm gửi email có attachment


func composeEmail(to email: String, subject: String, body: String, attachmentPath: String? = nil) {
    guard MFMailComposeViewController.canSendMail() else {
        print("Thiết bị không cấu hình tài khoản Mail")
        // Fallback: mailto: URL scheme
        return
    }
    
    let mailVC = MFMailComposeViewController()
    mailVC.mailComposeDelegate = self
    mailVC.setToRecipients([email])
    mailVC.setSubject(subject)
    mailVC.setMessageBody(body, isHTML: true)
    
    // Đính kèm file PDF từ Documents/Temp directory
    if let path = attachmentPath, let fileData = NSData(contentsOfFile: path) {
        mailVC.addAttachmentData(fileData as Data, mimeType: "application/pdf", fileName: "attachment.pdf")
    }
    
    present(mailVC, animated: true)
}

3. Delegate xử lý kết quả


func mailComposeController(_ controller: MFMailComposeViewController, 
                           didFinishWith result: MFMailComposeResult, 
                           error: Error?) {
    controller.dismiss(animated: true)
    
    switch result {
    case .sent: print("Email đã gửi")
    case .saved: print("Email đã lưu nháp")
    case .cancelled: print("User hủy gửi")
    case .failed: print("Gửi thất bại: \(error?.localizedDescription ?? "")")
    @unknown default: break
    }
}

4. Gọi khi tap button


@IBAction func sendEmailTapped(_ sender: UIButton) {
    let pdfPath = "\(NSTemporaryDirectory())report.pdf"
    // Đảm bảo file tồn tại tại path này
    composeEmail(to: "recipient@example.com", 
                 subject: "Báo cáo", 
                 body: "Kính gửi,
Đính kèm báo cáo.", attachmentPath: pdfPath) }

Kết quả

Cách gửi email có đính kèm file (attachment) bằng Swift

Lưu ý

  • Cần ít nhất 1 tài khoản Mail được cấu hình trong Settings > Mail trên thiết bị.
  • File đính kèm phải tồn tại tại đường dẫn cục bộ (local path).
  • Không chạy trên Simulator (không có Mail app). Test trên device thật.
  • Kích thước attachment tối đa tuỳ nhà cung cấp email (thường 20-25MB).
  • MIME type phổ biến: application/pdf, image/jpeg, image/png, text/csv.