Skip to content

Instantly share code, notes, and snippets.

@takashi1975
Created January 15, 2018 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takashi1975/28c1e202021c2727242458e91bd18e05 to your computer and use it in GitHub Desktop.
Save takashi1975/28c1e202021c2727242458e91bd18e05 to your computer and use it in GitHub Desktop.
添付ファイル付きメール送信例
/**
* メールの送信 ... 大まかには 以下の記事を参考
* https://qiita.com/kobaboy/items/1d8a5c01baf299a8573b
*
* Documentフォルダの realmファイル を添付したくて試した時のメモ
*/
extension ViewController: MFMailComposeViewControllerDelegate {
fileprivate func sendMail(subject: String, message: String) {
// let toRecipients = ["to@gmail.com"]
// let ccRecipients = ["cc@gmail.com"]
// let bccRecipients = ["Bcc1@gamil.com","Bcc2@gmail.com"]
let mailViewController = MFMailComposeViewController()
mailViewController.mailComposeDelegate = self
// mailViewController.setToRecipients(toRecipients)
// mailViewController.setCcRecipients(ccRecipients)
// mailViewController.setBccRecipients(bccRecipients)
//件名・本文
mailViewController.setSubject(subject)
mailViewController.setMessageBody(message, isHTML: false)
//添付ファイル
//Documentフォルダのパス
if let documentDirectoryFileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
// ファイルパス ... ディレクトリのパスにファイル名をつなげてファイルのフルパスを作る
let realmFileName = "default.realm"
let targetFilePath = documentDirectoryFileURL.appendingPathComponent(realmFileName)
do {
//realmファイルの送信
//TODO: mimeTypeの設定 "text/csv" ? (バイナリフィルの指定がわからない...)
let data = try Data(contentsOf: targetFilePath)
mailViewController.addAttachmentData(data, mimeType: "realm/binary", fileName: realmFileName)
} catch {
print("error ...")
}
}
self.present(mailViewController, animated: true, completion: nil)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case .sent:
break
default:
break
}
self.dismiss(animated: true, completion: nil)
}
}
@takashi1975
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment