1 先导入头文件
import MessageUI
2 写逻辑
if MFMailComposeViewController.canSendMail() {
let controller = MFMailComposeViewController()
//设置代理
controller.mailComposeDelegate = self
//设置主题
controller.setSubject(NSLocalizedString("Contact Us", comment: "Contact Us"))
//设置收件人
controller.setToRecipients(["hangge@qq.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.present(controller, animated: true, completion: nil)
}else{
let tip = NSLocalizedString("本设备不能发送邮件", comment: "")
print("\(tip)")
ProgressHUD.showError(tip, interaction: true)
}
3 写代理
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
// controller.dismiss(animated: true, completion: nil)
self.dismiss(animated: true, completion: nil)
switch result {
case .cancelled:
let tip = NSLocalizedString("邮件已取消", comment: "")
print("\(tip)")
ProgressHUD.showError(tip, interaction: true)
break
case .saved:
let tip = NSLocalizedString("邮件已保存", comment: "")
print("\(tip)")
ProgressHUD.show(tip, interaction: true)
case .sent:
let tip = NSLocalizedString("邮件已发送", comment: "")
print("\(tip)")
ProgressHUD.showSuccess(tip, interaction: true)
case .failed:
let tip = NSLocalizedString("邮件发送失败", comment: "")
print("\(tip)")
ProgressHUD.showError(tip, interaction: true)
@unknown default:
let tip = NSLocalizedString("邮件没有发送", comment: "邮件没有发送")
print("\(tip)")
ProgressHUD.showError(tip, interaction: true)
}
}
网友评论