ส่งอีเมลพร้อมไฟล์แนบด้วย MFMailComposeViewController
ใช้ MessageUI framework เพื่อเปิด Mail Composer แบบ Native พร้อมแนบไฟล์
ขั้นตอนที่ 1: สร้างโปรเจกต์และ Import Framework
Xcode → Single View App → ชื่อ "EmailAttachment"
Import MessageUI ใน ViewController.swift
ขั้นตอนที่ 2: Conform Protocol
class ViewController: UIViewController, MFMailComposeViewControllerDelegate
ขั้นตอนที่ 3: เพิ่มไฟล์ตัวอย่างในโปรเจกต์
ลากไฟล์ (เช่น sampleData.json) เข้า Project Navigator → ติ๊ก "Copy items if needed"
ขั้นตอนที่ 4: สร้าง IBAction สำหรับปุ่มส่งเมล
@IBAction func btnSendMail(_ sender: Any) {
guard MFMailComposeViewController.canSendMail() else {
print("Email cannot be sent - ไม่มีการตั้งค่า Mail บนอุปกรณ์")
// แสดง Alert แจ้งผู้ใช้
return
}
let mail = MFMailComposeViewController()
mail.setToRecipients(["test@gmail.com"])
mail.setSubject("GREETING")
mail.setMessageBody("Welcome to 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)
}
ขั้นตอนที่ 5: Implement Delegate Method
func mailComposeController(_ controller: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult,
error: Error?) {
if let error = error {
print("Error: \(error.localizedDescription)")
}
switch result {
case .cancelled: print("Cancelled")
case .sent: print("Mail sent successfully")
case .failed: print("Sending mail failed")
case .saved: print("Draft saved")
@unknown default: break
}
controller.dismiss(animated: true)
}
ขั้นตอนที่ 6: ทดสอบบนอุปกรณ์จริง
- Simulator ไม่สามารถส่งเมลได้ (canSendMail จะคืนค่า false)
- ต้องทดสอบบน iPhone/iPad จริงที่ตั้งค่า Mail account ไว้แล้ว
โค้ดเต็มรูปแบบ
import UIKit
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBAction func btnSendMail(_ sender: Any) {
guard MFMailComposeViewController.canSendMail() else { return }
let mail = MFMailComposeViewController()
mail.setToRecipients(["test@gmail.com"])
mail.setSubject("GREETING")
mail.setMessageBody("Welcome to 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?) {
controller.dismiss(animated: true)
}
}
Mime Type พร้อมใช้งาน
| File Type | Mime Type |
|---|---|
| JSON | application/json |
| application/pdf | |
| PNG | image/png |
| JPEG | image/jpeg |
| Plain Text | text/plain |