I want to use swift to implement in-app email. When I click the button, the email window pops up. However, I am unable to send my email. Moreover, after I click cancel-delete draft, I cannot go back to the original screen.
import UIkit
import MessageUI
class Information : UIViewController, MFMailComposeViewControllerDelegate{
var myMail: MFMailComposeViewController!
@IBAction func sendReport(sender : AnyObject) {
if(MFMailComposeViewController.canSendMail()){
myMail = MFMailComposeViewController()
//myMail.mailComposeDelegate
// set the subject
myMail.setSubject("My report")
//To recipients
var toRecipients = ["lipeilin@gatech.edu"]
myMail.setToRecipients(toRecipients)
//CC recipients
var ccRecipients = ["tzhang85@gatech.edu"]
myMail.setCcRecipients(ccRecipients)
//CC recipients
var bccRecipients = ["tzhang85@gatech.edu"]
myMail.setBccRecipients(ccRecipients)
//Add some text to the message body
var sentfrom = "Email sent from my app"
myMail.setMessageBody(sentfrom, isHTML: true)
//Include an attachment
var image = UIImage(named: "Gimme.png")
var imageData = UIImageJPEGRepresentation(image, 1.0)
myMail.addAttachmentData(imageData, mimeType: "image/jped", fileName: "image")
//Display the view controller
self.presentViewController(myMail, animated: true, completion: nil)
}
else{
var alert = UIAlertController(title: "Alert", message: "Your device cannot send emails", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
func mailComposeController(controller: MFMailComposeViewController!,
didFinishWithResult result: MFMailComposeResult,
error: NSError!){
switch(result.value){
case MFMailComposeResultSent.value:
println("Email sent")
default:
println("Whoops")
}
self.dismissViewControllerAnimated(true, completion: nil)
}
}
This is how I have composed my email with attached PDF file document.
Just to test this example you need to drag and drop a sample PDF named "All_about_tax.pdf"
In case anyone is looking for a non MFMailCompose option, here's what I did to send using Gmail's SMTP servers.
MyApp-Briding-Header.h
Objective-C Briding Header
->Debug
(i.e.MyApp/MyApp-Bridging-Header.h
Select all .m files and click enter. Type
-fno-objc-arc
and hit enter.Use this code to send email:
Hope it helps someone. I didn't want to use the MFMailCompose option because I didn't want to have to prompt the user.
Since you haven't set the current view controller as the
mailComposeDelegate
ofmyMail
, themailComposeController:didFinishWithResult
method isn't being called. After you initmyMail
, make sure to add:and you'll be good to go