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

Cách gửi email từ ứng dụng iPhone

Để gửi email từ ứng dụng iOS, chúng ta không thể gửi trực tiếp trừ khi app là mail client dùng MessageUI. Thay vào đó, mở ứng dụng Mail mặc định hoặc trình soạn thảo mail với nội dung điền sẵn (pre-filled). Có 2 cách:

Cách 1: URL Scheme "mailto:" (Đơn giản, không cần framework)

func sendEmail(to email: String) {
    let urlString = "mailto:\(email)?subject=\(subject)&body=\(body)"
        .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
    
    if let url = URL(string: urlString) {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url)
        } else {
            UIApplication.shared.openURL(url)
        }
    }
}

Mở app Mail (hoặc Gmail, Outlook nếu user set default) với to/subject/body đã điền sẵn.

Cách 2: MFMailComposeViewController (MessageUI Framework - Nâng cao)

Cho phép compose email trong app, không cần chuyển app, hỗ trợ đính kèm file, HTML body.

import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
    
    func sendMFMail(to email: String) {
        guard MFMailComposeViewController.canSendMail() else {
            print("Thiết bị không cấu hình tài khoản mail")
            // Fallback: dùng mailto:
            return
        }
        
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients([email])
        mailVC.setSubject("Test gửi email")
        mailVC.setMessageBody("Nội dung email test", isHTML: false)
        
        // Đính kèm file (ví dụ PDF)
        if let pdfPath = Bundle.main.path(forResource: "document", ofType: "pdf"),
           let pdfData = NSData(contentsOfFile: pdfPath) {
            mailVC.addAttachmentData(pdfData as Data, mimeType: "application/pdf", fileName: "document.pdf")
        }
        
        present(mailVC, animated: true)
    }
    
    // Delegate method
    func mailComposeController(_ controller: MFMailComposeViewController, 
                               didFinishWith result: MFMailComposeResult, 
                               error: Error?) {
        controller.dismiss(animated: true)
    }
}

So sánh

Tiêu chímailto: URLMFMailComposeViewController
FrameworkKhông cầnMessageUI
UIChuyển sang app MailModal trong app
Đính kèm fileKhông hỗ trợHỗ trợ
HTML BodyKhó kiểm soátHỗ trợ (isHTML: true)
Yêu cầuUser có app mailUser có tài khoản mail trong Settings
SimulatorKhông chạyKhông chạy (không có Mail app)

Lưu ý: Cả 2 cách đều không chạy trên Simulator (Simulator không có Mail app). Cần test trên thiết bị thật.