码迷,mamicode.com
首页 > 编程语言 > 详细

Swift - 邮件发送功能的实现

时间:2015-09-28 13:02:05      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

使用MessageUI.framework框架除了可以发送短信,还能发送Email,步骤如下:

(1)首先判断设备是否有发送邮件功能
(2)如果设备允许发送邮件,创建一个MFMailComposeViewController视图控制器,并对其设置邮件标题,正文内容,收件人,附件等。
(3)邮件发送后,会执行回调代理方法,可以获取发送结果(成功,失败或取消)
 
效果图如下:
技术分享

代码如下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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(["a1@hangge.com","a2@hangge.com"])
            //设置抄送人
            controller.setCcRecipients(["b1@hangge.com","b2@hangge.com"])
            //设置密送人
            controller.setBccRecipients(["c1@hangge.com","c2@hangge.com"])
             
            //添加图片附件
            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{
            println("本设备不能发送邮件")
        }
    }
     
    //发送邮件代理方法
    func mailComposeController(controller: MFMailComposeViewController!,
        didFinishWithResult result: MFMailComposeResult, error: NSError!) {
        controller.dismissViewControllerAnimated(true, completion: nil)
             
        switch result.value{
            case MFMailComposeResultSent.value:
                println("邮件已发送")
            case MFMailComposeResultCancelled.value:
                println("邮件已取消")
            case MFMailComposeResultSaved.value:
                println("邮件已保存")
            case MFMailComposeResultFailed.value:
                println("邮件发送失败")
            default:
                println("邮件没有发送")
                break
        }
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Swift - 邮件发送功能的实现

标签:

原文地址:http://www.cnblogs.com/Free-Thinker/p/4843608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!