Failed on using Swift to implement in-app email
Asked Answered
R

3

10

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 = ["[email protected]"]
            myMail.setToRecipients(toRecipients)

            //CC recipients
            var ccRecipients = ["[email protected]"]
            myMail.setCcRecipients(ccRecipients)

            //CC recipients
            var bccRecipients = ["[email protected]"]
            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)

}
}
Radke answered 17/6, 2014 at 3:28 Comment(1)
You never set the mailComposeDelegate.Selfoperating
T
10

Since you haven't set the current view controller as the mailComposeDelegate of myMail, the mailComposeController:didFinishWithResult method isn't being called. After you init myMail, make sure to add:

myMail.mailComposeDelegate = self

and you'll be good to go

Throughout answered 17/6, 2014 at 4:7 Comment(3)
That works! Thank you very much! However, after I click "send", it seems that the email is not sent. Could I ask how to send my email?Radke
Are you doing this on the device or the simulator?Throughout
Oh I realize that I am doing this on the simulator...Thank you very much!Radke
R
1

In case anyone is looking for a non MFMailCompose option, here's what I did to send using Gmail's SMTP servers.

  1. Download a zip of this repo: https://github.com/jetseven/skpsmtpmessage
  2. Drag and drop the files under SMTPLibrary into your XCode project
  3. Create a new header file - MyApp-Briding-Header.h
  4. Replace new header file with this:
#import "Base64Transcoder.h"
#import "HSK_CFUtilities.h"
#import "NSData+Base64Additions.h"
#import "NSStream+SKPSMTPExtensions.h"
#import "SKPSMTPMessage.h"
  1. Go to Project(Targets > MyApp on the left)/Build Settings/Swift Compiler - Code Generation
  2. Add path to header file under Objective-C Briding Header -> Debug (i.e. MyApp/MyApp-Bridging-Header.h
  3. Go to Project/Build Phases/Compile Sources
  4. Select all .m files and click enter. Type -fno-objc-arc and hit enter.

  5. Use this code to send email:

var mail = SKPSMTPMessage()       
mail.fromEmail = "[email protected]"
mail.toEmail = "[email protected]"
mail.requiresAuth = true
mail.login = "[email protected]"
mail.pass = "password"
mail.subject = "test subject"
mail.wantsSecure = true
mail.relayHost = "smtp.gmail.com"

mail.relayPorts = [587]

var parts: NSDictionary = [
            "kSKPSMTPPartContentTypeKey": "text/plain; charset=UTF-8",
            "kSKPSMTPPartMessageKey": "test message",
]

mail.parts = [parts]

mail.send()

Hope it helps someone. I didn't want to use the MFMailCompose option because I didn't want to have to prompt the user.

Roderickroderigo answered 20/7, 2015 at 14:49 Comment(0)
H
0

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"

@IBAction func sendEmail(sender: UIButton)
    {
        //Check to see the device can send email.
        if( MFMailComposeViewController.canSendMail() )
        {
            print("Can send email.")

            let mailComposer = MFMailComposeViewController()
            mailComposer.mailComposeDelegate = self

            //Set to recipients
            mailComposer.setToRecipients(["your email id here"])

            //Set the subject
            mailComposer.setSubject("Tax info document pdf")

            //set mail body
            mailComposer.setMessageBody("This is what they sound like.", isHTML: true)

            if let filePath = NSBundle.mainBundle().pathForResource("All_about_tax", ofType: "pdf")
            {
                print("File path loaded.")

                if let fileData = NSData(contentsOfFile: filePath)
                {
                    print("File data loaded.")
                    mailComposer.addAttachmentData(fileData, mimeType: "application/pdf", fileName: "All_about_tax.pdf")

                }
            }

            //this will compose and present mail to user
            self.presentViewController(mailComposer, animated: true, completion: nil)
        }
        else
        {
            print("email is not supported")
        }
    }



    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
Hendrika answered 1/7, 2016 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.