Swift - 实现发送邮件功能

原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_792.html
使用MessageUI.framework框架除了可以发送短信,还能发送Email,步骤如下:
(1)首先判断设备是否有发送邮件功能
(2)如果设备允许发送邮件,创建一个MFMailComposeViewController视图控制器,并对其设置邮件标题,正文内容,收件人,附件等。
(3)邮件发送后,会执行回调代理方法,可以获取发送结果(成功,失败或取消)

效果图如下:
Swift - 实现发送邮件功能_第1张图片

代码如下:

import UIKit
import MessageUI

class ViewController: UIViewController ,UINavigationControllerDelegate,
MFMailComposeViewControllerDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()

        //首先要判断设备具不具备发送邮件功能
        if MFMailComposeViewController.canSendMail(){
            let controller = MFMailComposeViewController()
            //设置代理
            controller.mailComposeDelegate = self
            //设置主题
            controller.setSubject("我是邮件标题")
            //设置收件人
            controller.setToRecipients(["[email protected]","[email protected]"])
            //设置抄送人
            controller.setCcRecipients(["[email protected]","[email protected]"])
            //设置密送人
            controller.setBccRecipients(["[email protected]","[email protected]"])

            //添加图片附件
// var path = NSBundle.mainBundle().pathForResource("hangge.png", ofType: "")
// var myData = NSData(contentsOfFile: path!)
// controller.addAttachmentData(myData, mimeType: "image/png", fileName: "swift.png")

            //设置邮件正文内容(支持html)
            controller.setMessageBody("我是邮件正文", isHTML: false)

            //打开界面
            self.presentViewController(controller, animated: true, completion: nil)
        }else{
            print("本设备不能发送邮件")
        }
    }

    //发送邮件代理方法
    func mailComposeController(controller: MFMailComposeViewController,
        didFinishWithResult result: MFMailComposeResult, error: NSError?) {
            controller.dismissViewControllerAnimated(true, completion: nil)

            switch result.rawValue{
                case MFMailComposeResultSent.rawValue:
                    print("邮件已发送")
                case MFMailComposeResultCancelled.rawValue:
                    print("邮件已取消")
                case MFMailComposeResultSaved.rawValue:
                    print("邮件已保存")
                case MFMailComposeResultFailed.rawValue:
                    print("邮件发送失败")
            default:
                print("邮件没有发送")
                break
            }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

你可能感兴趣的:(邮件,swift,电子邮件)