Skip to content

Instantly share code, notes, and snippets.

@liaujianjie
Last active August 2, 2016 08:17
Show Gist options
  • Save liaujianjie/7bce4123ded2209c0935 to your computer and use it in GitHub Desktop.
Save liaujianjie/7bce4123ded2209c0935 to your computer and use it in GitHub Desktop.
Swift convenience NSURL extension for composing mailto urls
import Foundation
extension NSURL {
/**
Convenience class method for composing an `NSURL` for creating mail links with the `mailto` scheme.
- parameter receipients: Email receipients
- parameter cc: Email carbon copy receipients. (optional)
- parameter bcc: Email blind carbon copy receipients (optional)
- parameter subject: Subject title of the email (optional)
- parameter body: Body message of the email (optional)
- returns: `NSURL` composed by the provided parameters using the `mailto` scheme.
*/
class func mailTo(receipients: [String], cc: [String]?, bcc: [String]?, subject: String?, body: String?) -> NSURL? {
let emailAddressesString = receipients.joinWithSeparator(",")
let ccString = cc?.joinWithSeparator(",")
let bccString = bcc?.joinWithSeparator(",")
let components = NSURLComponents(string: "mailto:" + emailAddressesString)
components?.queryItems == components?.queryItems ?? []
["cc": ccString, "bcc": bccString, "subject": subject, "body": body].forEach { (param, value) -> Void in
if !((value ?? "").isEmpty) {
components?.queryItems?.append(NSURLQueryItem(name: param, value: value))
}
}
return components?.URL
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment