Skip to content

Instantly share code, notes, and snippets.

@kellyegan
Last active April 2, 2023 00:57
Show Gist options
  • Save kellyegan/49e3e11fe68b5e6b5360 to your computer and use it in GitHub Desktop.
Save kellyegan/49e3e11fe68b5e6b5360 to your computer and use it in GitHub Desktop.
Send emails with attachments in iOS using Swift
//
// ViewController.swift
// SendEmailWithAttachment
//
// Created by Kelly Egan on 3/17/15.
// Copyright (c) 2015 Kelly Egan. All rights reserved.
//
import UIKit
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBOutlet weak var emailButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sendEmail(sender: UIButton) {
//Check to see the device can send email.
if( MFMailComposeViewController.canSendMail() ) {
println("Can send email.")
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
//Set the subject and message of the email
mailComposer.setSubject("Have you heard a swift?")
mailComposer.setMessageBody("This is what they sound like.", isHTML: false)
if let filePath = NSBundle.mainBundle().pathForResource("swifts", ofType: "wav") {
println("File path loaded.")
if let fileData = NSData(contentsOfFile: filePath) {
println("File data loaded.")
mailComposer.addAttachmentData(fileData, mimeType: "audio/wav", fileName: "swifts")
}
}
self.presentViewController(mailComposer, animated: true, completion: nil)
}
}
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
@Rushabh5
Copy link

Rushabh5 commented Mar 9, 2017

I want to download through URL from backend side so i don't know file type so what is the value are passed, And yes URL param like images, pdf, mp3 any type of file.

@AshvinGudaliya
Copy link

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