一.需要导入messageUI.Frameworks(#import<messageUI/messageUI.h>)
二.步骤:
if MFMailComposeViewController.canSendMail() {
let mailCompose = MFMailComposeViewController()
// 收邮件人
mailCompose.setToRecipients(["toRecipients@163.com"])
// 抄送人
mailCompose.setCcRecipients(["ccRecipients@163.com"])
// 密送人
mailCompose.setBccRecipients(["bccRecipients@163.com"])
mailCompose.setSubject("邮箱主题")
mailCompose.setMessageBody("邮箱内容", isHTML: false)
// 添加一张图片
if let addPic = UIImage(named: "") {
//关于mimeType:http://www.iana.org/assignments/media-types/index.html
mailCompose.addAttachmentData(UIImagePNGRepresentation(addPic)!, mimeType: "", fileName: "")
}
mailCompose.mailComposeDelegate = self
self.present(mailCompose, animated: true, completion: nil)
} else {
// 用户没有设置邮箱账号
var str: String = ""
str += "mailto:toRecipients@163.com"
str += "?cc=ccRecipients@163.com"
str += "&bcc=bccRecipients@163.com"
str += "&subjec=邮箱主题"
str += "&body=邮箱内容"
let url = str.utf8.url!
//"mailto:*@163.com?cc=second@example.com,third@example.com&subject=myemail!"
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
}
代理(MFMailComposeViewControllerDelegate):
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
print(result)
controller.dismiss(animated: true, completion: nil)
}