对于我的应用程序,我需要能够直接从应用程序发送带有各种类型附件的电子邮件。我找到了一些解决方案并对其进行了测试。
如果我尝试从我的应用程序发送 .zip 或 .txt 文件,它工作正常。但我无法发送“.swift”类型的文件。有人知道它是如何工作的吗?
这是我的代码:
import UIKit
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
var EmailTxt = ""
override func viewDidLoad() {
super.viewDidLoad()
setEmailTxt()
sendEmail()
view.backgroundColor = UIColor.lightGray
}
func sendEmail() {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(["sgamesro@gmail.com"])
mail.setMessageBody(EmailTxt, isHTML: true)
mail.setSubject("test email")
if let filePath = Bundle.main.path(forResource: "test", ofType: "swift") {
print("# File path loaded.")
if let fileData = NSData(contentsOfFile: filePath) {
print("File data loaded.")
mail.addAttachmentData(fileData as Data, mimeType: "swift", fileName: "test.swift")
}
}
present(mail, animated: true)
} else {
// show failure alert
print("# func sendEmail() Mistake")
}
}
func setEmailTxt() {
EmailTxt = "<p>test line 01</p> <p>test line 02</p>" //<p>This is some text in a paragraph.</p>
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
}