"Send email with attachments on iPhone"

Mon 11 May 2009

//Additionals acctions to do:

//  - add source code from attached ZIP;

//  - add CFNetwork.framework to project;

//  - your class should implement <SKPSMTPMessageDelegate> protocol.

 

#import "SKPSMTPMessage.h"

#import "NSData+Base64Additions.h"

#import <SystemConfiguration/SCNetworkReachability.h>

#include <netinet/in.h>

 

- (void)sendMessageInBack:(id)anObject{

NSLog(@"Start Sending");

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"tmp.pdf"];

 

NSData *dataObj = [NSData dataWithContentsOfFile:writableDBPath];

SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];

testMsg.fromEmail = @"from@gmail.com";

testMsg.toEmail = emailField.text;

testMsg.relayHost = @"smtp.gmail.com";

testMsg.requiresAuth = YES;

testMsg.login = @"yourlogin";

testMsg.pass = @"yourpassword";

testMsg.subject = @"Some subject";

testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!

// Only do this for self-signed certs!

// testMsg.validateSSLChain = NO;

testMsg.delegate = self;

NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,

  @"Some text to include in body",kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];

NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"filenametoshow.pdf\"",kSKPSMTPPartContentTypeKey,

@"attachment;\r\n\tfilename=\"filenametoshow.pdf\"",kSKPSMTPPartContentDispositionKey,[dataObj encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];

testMsg.parts = [NSArray arrayWithObjects:plainPart,

vcfPart,

nil];

[testMsg send];

 

}

 

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

[message release];

// open an alert with just an OK button

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Unable to send email"

  delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];

[alert show];

[alert release];

NSLog(@"delegate - error(%d): %@", [error code], [error localizedDescription]);

}

 

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

    [message release];

    

    NSLog(@"delegate - message sent");

}

 

SMTPSend.zip (16.19 kb)