这里注意一定要使用真?。 应为模拟器中没有邮件。 反正我的是没有,谁难受谁知道
//
// ViewController.swift
// Dome2test
//
// Created by 郭文亮 on 2018/11/21.
// Copyright © 2018年 finalliang. All rights reserved.
//
import UIKit
//导入框架:发送短信或邮件
import MessageUI
//添加邮件编辑视图代理协议MFMailComposeViewControllerDelegate
class ViewController: UIViewController ,MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
//使用MessageUI框架 创建并发送一封带有附件的邮件
let button = UIButton(frame: CGRect(x: 40, y: 88, width: 240, height: 44))
button.backgroundColor = UIColor.purple
button.setTitle("write a mail", for: UIControlState())
button.addTarget(self, action: #selector(ViewController.sendEmail), for: UIControlEvents.touchUpInside)
self.view.addSubview(button)
}
@objc func sendEmail(){
if (!MFMailComposeViewController.canSendMail()) {
let wAlertView = UIAlertController(title: "不能发送邮件", message: "请检查邮件设置", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: nil)
wAlertView.addAction(action)
self.present(wAlertView,animated: true,completion: nil)
return;
}
//初始化一个邮件编写视图控制器
let mailBox = MFMailComposeViewController()
//创建一个数组用来设置收件人的邮箱
let recipients = ["275909862@qq.com"]
//设置目标邮箱
mailBox.setToRecipients(recipients)
//设置邮件标题
mailBox.setSubject("Information!")
//设置邮件内容
mailBox.setMessageBody("<font color='red'Hello world</font>", isHTML: true)
//从项目加载一张图片作为附件。压缩为二进制数据格式
let image = UIImage(named: "Pic")
let imageData = UIImagePNGRepresentation(image!)
//将转换格式后的数据对象作为邮件的附件
mailBox.addAttachmentData(imageData!, mimeType: "", fileName: "Pic.png")
//设置邮件发送的监听对象为当前视图的控制器对象 ,显示邮件的编辑视图
mailBox.mailComposeDelegate = self
self.present(mailBox, animated: true,completion: nil)
}
//实现代理 响应邮件发送的结果事件
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
//遍历邮件的集中发送状态, 首先处理用户取消邮件发送时的情况
if (result == MFMailComposeResult.cancelled){
print(">>> 取消邮件发送")
}else if (result == MFMailComposeResult.failed){
print(">>> 邮件发送失败")
}else if (result == MFMailComposeResult.saved){
print(">>>邮件保存成功")
}else if (result == MFMailComposeResult.sent){
print("邮件发送成功")
}
//发送邮件后关闭邮件视图控制器
controller.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}