ไม่สามารถส่งอีเมลโดยตรงจากแอปได้ (เว้นแต่เป็น Mail App) แต่สามารถเปิด Mail App พร้อมข้อมูล Pre-filled หรือใช้ MFMailComposeViewController
วิธีที่ 1: URL Scheme (mailto:) - เรียบง่าย
func sendEmail(to email: String, subject: String? = nil, body: String? = nil) {
var urlComponents = URLComponents()
urlComponents.scheme = "mailto"
urlComponents.path = email
var queryItems: [URLQueryItem] = []
if let subject = subject { queryItems.append(URLQueryItem(name: "subject", value: subject)) }
if let body = body { queryItems.append(URLQueryItem(name: "body", value: body)) }
urlComponents.queryItems = queryItems.isEmpty ? nil : queryItems
guard let url = urlComponents.url else { return }
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}
}
// ใช้งาน
sendEmail(to: "support@example.com", subject: "Feedback", body: "Hello!")
วิธีที่ 2: MFMailComposeViewController (MessageUI) - ควบคุมได้มากกว่า
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
func sendEmail() {
guard MFMailComposeViewController.canSendMail() else {
print("Mail not configured")
// Fallback ไป mailto:
sendEmailFallback()
return
}
let composer = MFMailComposeViewController()
composer.mailComposeDelegate = self
composer.setToRecipients(["support@example.com"])
composer.setSubject("Feedback from App")
composer.setMessageBody("Hello, this is feedback.", isHTML: false)
// Attach ไฟล์
if let data = "Log data".data(using: .utf8) {
composer.addAttachmentData(data, mimeType: "text/plain", fileName: "log.txt")
}
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
}
}
}
เปรียบเทียบ
| คุณสมบัติ | mailto: | MFMailComposeViewController |
|---|---|---|
| Attachment | ไม่ได้ | ได้ |
| HTML Body | ได้ (จำกัด) | ได้ |
| Callback Result | ไม่มี | มี (Delegate) |
| ต้องมี Mail App | ใช่ | ใช่ |
| ทำงานบน Simulator | ไม่ได้ | ไม่ได้ |
หมายเหตุ
- ทั้งสองวิธี ไม่ทำงานบน Simulator (ไม่มี Mail App)
- MFMailComposeViewController ต้อง Import
MessageUI - iOS 13+ ใช้
UIApplication.shared.open(url)แทนopenURL(Deprecated)