ใช้ MFMailComposeViewController (MessageUI Framework) ส่งอีเมลพร้อม Attachment
Setup
- Project Settings → Signing & Capabilities → + Capability → Mail (ถ้าจำเป็น)
- Import
MessageUI - Conform
MFMailComposeViewControllerDelegate
โค้ดส่งอีเมลพร้อมไฟล์ PDF
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
func sendEmailWithAttachment(to email: String, subject: String, body: String, pdfURL: URL) {
guard MFMailComposeViewController.canSendMail() else {
print("Mail not configured")
// Fallback: mailto: หรือแชร์ไฟล์
return
}
let composer = MFMailComposeViewController()
composer.mailComposeDelegate = self
composer.setToRecipients([email])
composer.setSubject(subject)
composer.setMessageBody(body, isHTML: true)
// Attach PDF
if let pdfData = try? Data(contentsOf: pdfURL) {
composer.addAttachmentData(pdfData, mimeType: "application/pdf", fileName: "document.pdf")
}
// Attach Image
if let image = UIImage(named: "logo"), let imageData = image.pngData() {
composer.addAttachmentData(imageData, mimeType: "image/png", fileName: "logo.png")
}
present(composer, animated: true)
}
// Delegate
func mailComposeController(_ controller: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult,
error: Error?) {
controller.dismiss(animated: true)
switch result {
case .sent: print("✅ Sent")
case .saved: print("💾 Saved as draft")
case .cancelled: print("❌ Cancelled")
case .failed: print("💥 Failed: \(error?.localizedDescription ?? "")")
@unknown default: break
}
}
}
เรียกใช้งาน
@IBAction func sendEmailTapped(_ sender: UIButton) {
let pdfURL = Bundle.main.url(forResource: "report", withExtension: "pdf")!
sendEmailWithAttachment(
to: "client@example.com",
subject: "Monthly Report",
body: "Please find attached the monthly report.",
pdfURL: pdfURL
)
}
ข้อจำกัด
- ไม่ทำงานบน Simulator (ไม่มี Mail App)
- ต้องตั้งค่า Mail Account บน Device จริง
- ขนาด Attachment ขึ้นกับ Mail Server (โดยทั่วไป ~20-25MB)
- ไม่สามารถส่งอีเมล "โดยตรง" โดยไม่มี User Interaction (Apple Policy)
ทางเลือกอื่น
- Share Sheet:
UIActivityViewControllerแชร์ไฟล์ให้ User เลือก Mail App เอง - SMTP Library: ใช้ Library เช่น
SwiftSMTPสำหรับส่งโดยตรง (ต้องมี Credentials) - Backend API: ส่งข้อมูลไป Server ให้ Server ส่งอีเมลแทน (แนะนำสำหรับ Production)