Giới thiệu
Việc gửi email với tệp đính kèm là tính năng phổ biến trong nhiều ứng dụng. iOS cung cấp MFMailComposeViewController (framework MessageUI) để thực hiện việc này một cách chuẩn chuẩn và an toàn.
Yêu cầu
- Import
MessageUI. - Tuân thủ protocol
MFMailComposeViewControllerDelegate. - Thiết bị thật (simulator không hỗ trợ gửi mail).
- File đính kèm đã thêm vào project (Copy items if needed).
Các bước thực hiện
Bước 1: Tạo dự án
Xcode → New Project → Single View Application → Tên "EmailAttachment".
Bước 2: Thêm Button vào Storyboard

Bước 3: Tạo IBAction
@IBAction func btnSendMail(_ sender: Any) { }
Bước 4: Import MessageUI và conform Delegate
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate { ... }
Bước 5: Thêm file đính kèm vào project
Kéo file (ví dụ: sampleData.json) vào project navigator, chọn "Copy items if needed".

Bước 6: Viết hàm gửi mail
@IBAction func btnSendMail(_ sender: Any) {
guard MFMailComposeViewController.canSendMail() else {
print("Thiết bị không cấu hình tài khoản mail")
return
}
let mail = MFMailComposeViewController()
mail.setToRecipients(["test@gmail.com"])
mail.setSubject("CHÀO MỪNG")
mail.setMessageBody("Chào mừng đến với Tutorials Point!", isHTML: true)
mail.mailComposeDelegate = self
// Đính kèm file
if let filePath = Bundle.main.path(forResource: "sampleData", ofType: "json"),
let data = NSData(contentsOfFile: filePath) as Data? {
mail.addAttachmentData(data, mimeType: "application/json", fileName: "sampleData.json")
}
present(mail, animated: true)
}
Bước 7: Xử lý delegate (kết quả gửi)
func mailComposeController(_ controller: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult,
error: Error?) {
if let error = error {
print("Lỗi: \(error.localizedDescription)")
}
switch result {
case .cancelled: print("Người dùng hủy gửi")
case .sent: print("Gửi thành công")
case .failed: print("Gửi thất bại")
case .saved: print("Đã lưu nháp")
@unknown default: break
}
controller.dismiss(animated: true)
}
Bước 8: Chạy trên thiết bị thật

Mã nguồn hoàn chỉnh
import UIKit
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btnSendMail(_ sender: Any) {
guard MFMailComposeViewController.canSendMail() else {
print("Không thể gửi mail")
return
}
let mail = MFMailComposeViewController()
mail.setToRecipients(["test@gmail.com"])
mail.setSubject("CHÀO MỪNG")
mail.setMessageBody("Chào mừng đến với Tutorials Point!", isHTML: true)
mail.mailComposeDelegate = self
if let filePath = Bundle.main.path(forResource: "sampleData", ofType: "json"),
let data = NSData(contentsOfFile: filePath) as Data? {
mail.addAttachmentData(data, mimeType: "application/json", fileName: "sampleData.json")
}
present(mail, animated: true)
}
func mailComposeController(_ controller: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult,
error: Error?) {
if let error = error {
print("Lỗi: \(error.localizedDescription)")
}
switch result {
case .cancelled: print("Đã hủy")
case .sent: print("Đã gửi")
case .failed: print("Thất bại")
case .saved: print("Đã lưu nháp")
@unknown default: break
}
controller.dismiss(animated: true)
}
}
Lưu ý
- Mime type phổ biến:
application/pdf,image/png,image/jpeg,text/plain,application/zip. - Kích thước file đính kèm lớn có thể gây chậm khi trình bày mail composer.
- Luôn kiểm tra
canSendMail()trước khi present.