Monday 24 June 2013

Send e-mail in background from iOS Application SMTP gmail account

Method :
1. Import CFNetwork.framework to your project.
2. Include     #import "SKPSMTPMessage.h"
                    #import "NSData+Base64Additions.h" // for Base64 encoding

3. Include <SKPSMTPMessageDelegate> to your ViewController
4.  Download SKPSMTPMessage library from  


5. Drag and Drop "SMTPLibrary" folder you have downloaded to your project.



       Before proceeding, let you know that i am using sender/receiver email address and sender password hardcoded in the code for this example.But, you may grab this credentials from user, allowing them to input in some sort of forms(using UIViews).


-(void) sendEmailInBackground {
            NSLog(@"Start Sending");
            SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
            emailMessage.fromEmail = @"sender@gmail.com"; //sender email address
            emailMessage.toEmail = @"receiver@gmail.com";  //receiver email address
            emailMessage.relayHost = @"smtp.gmail.com";
            //emailMessage.ccEmail =@"your cc address";
           //emailMessage.bccEmail =@"your bcc address";
            emailMessage.requiresAuth = YES;
            emailMessage.login = @"sender@gmail.com"; //sender email address
            emailMessage.pass = @"Passwxxxx"; //sender email password
            emailMessage.subject =@"@"email subject header message";
            emailMessage.wantsSecure = YES; 
            emailMessage.delegate = self; // you must include <SKPSMTPMessageDelegate> to your class
           NSString *messageBody = @"your email body message";
         //for example :   NSString *messageBody = [NSString stringWithFormat:@"Tour Name: %@\nName: %@\nEmail: %@\nContact No: %@\nAddress: %@\nNote: %@",selectedTour,nameField.text,emailField.text,foneField.text,addField.text,txtView.text];
      // Now creating plain text email message
 NSDictionary *plainMsg = [NSDictionary
                        dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,                               
 messageBody,kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
  emailMessage.parts = [NSArray arrayWithObjects:plainMsg,nil];
        
            [emailMessage send];
     // sending email- will take little time to send so its better to use indicator with message showing sending...
}

Now, handling delegate methods :
// On success

-(void)messageSent:(SKPSMTPMessage *)message{

    NSLog(@"delegate - message sent");
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message sent." message:nil delegate:nilcancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show]; 
}
// On Failure

-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{

// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:[error localizedDescription] delegate:nilcancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
NSLog(@"delegate - error(%d): %@", [error code], [error localizedDescription]);
}


Before you proceed you need to do changes as below:
1. If your project ARC is enabled and library has ARC disabled code  then you can disable your project ARC by going through your project target -> Build Settings ->Objective-c Automatic Reference Counting -> set NO
Or, if you only want to disable ARC for those library files only then  you can do it as :  To disable ARC for source files in Xcode 4, select the project and the target in Xcode. Under the target "Build Phases" tab, expand the Compile Sources build phase, select the library source files(.m file), then press Enter to open an edit field, and type 
-fno-objc-arc as the compiler flag for those files.

2. If you have encountered compiling error like  this in pic :
Then solution is go to your project target -> Build Phases -> Compile Sources -> add your all the .m class of your SMTP library .

That's all.

Happy iCoding

4 comments:

  1. Hello Dear,
    I follow up the steps as mentioned for this feature, however It is not working at my end it dont showing any error message or success message

    ReplyDelete
  2. I implement this tutorial step by step i am not getting any error message and successful message
    always it shows the delegate - error(-5): Timeout sending message. what should i do? please help me out.

    I am using xcode 7.3 and OS 10.11.4 latest version.
    Thank You for the feedbacks.

    ReplyDelete
  3. it not showing any success or error message

    ReplyDelete
  4. Good one. Now I have successfully using the SMTP server as described.

    ReplyDelete