yu-App's blog

iPhoneアプリ開発におけるメモ的なもの。

swift2.0 メールを送信する

まずは準備

import MessageUI

class ViewController: UIViewController,MFMailComposeViewControllerDelegate {

・
・
・


func sendMail() {
        //メールを送信できるかチェック
        if MFMailComposeViewController.canSendMail()==false {
            print("Email Send Failed")
            return
        }
        
        let mailViewController = MFMailComposeViewController()
        let toRecipients = ["test@test.com"]
        
        
        mailViewController.mailComposeDelegate = self
        mailViewController.setSubject("メールの件名")
        mailViewController.setToRecipients(toRecipients) //宛先メールアドレスの表示
        mailViewController.setMessageBody("メールの本文", isHTML: false)
        
        
        self.presentViewController(mailViewController, animated: true, completion: nil)
    }

    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        
        switch result.rawValue {
        case MFMailComposeResultCancelled.rawValue:
            
            print("Email Send Cancelled")
            break
        case MFMailComposeResultSaved.rawValue:
            print("Email Saved as a Draft")
            break
        case MFMailComposeResultSent.rawValue:
            print("Email Sent Successfully")
            break
        case MFMailComposeResultFailed.rawValue:
            print("Email Send Failed")
            break
        default:
            break
        }
        
        self.dismissViewControllerAnimated(true, completion: nil)
    }