I am using NSMutableURLRequest to send POST data to a server-side PHP script that sends emails using SendGrid. This works just fine. However, I have no idea how to package UIImagedata properly to send as an attachment. Here is my current code:
// Choose an image from your photo library
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
chosenImage = info[UIImagePickerControllerEditedImage]; // chosenImage = UIImage
pickedData = UIImagePNGRepresentation(chosenImage); // pickedData = NSData
attachment = TRUE;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
-(void)sendMail {
toEmailAddress = @"blabla@blabla.com";
subject = @"Some Subject";
message = @"Some message...";
fullName = @"Mister Bla Bla";
if (attachment == TRUE) {
// Create NSData object as PNG image data from camera image
NSString *picAttachment = [NSString stringWithFormat:@"%lu",(unsigned long)[pickedData length]];
NSString *picName = @"Photo";
post = [NSString stringWithFormat:@"&toEmailAddress=%@&subject=%@&message=%@&fullName=%@&picAttachment=%@&picName=%@", toEmailAddress, subject, message, fullName, picAttachment, picName];
} else {
post = [NSString stringWithFormat:@"&toEmailAddress=%@&subject=%@&message=%@&fullName=%@", toEmailAddress, subject, message, fullName];
}
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.someURL.com/sendgrid.php"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
// send the POST request, and read the reply by creating a new NSURLSession:
NSURLSession *conn = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[conn dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply); // Return response from PHP script on server.
}] resume];
}
If you research this question, you may find that there is an existing iOS SendGrid lib. Unfortunately, this is not the answer. The folks at SendGrid tell me not to use the lib because of a security concern.