Send email from iOS app using SendGrid - image

I am trying to to use mail api from sendgrid.com but everytime it finishes with failure block.
Also I don't understand how to send the image as an attachment in the email. Can anybody tell me whats wrong in below code & how can I send image ? I am using below code for now
-(void)sendEmail
{
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:#"username" forKey:#"api_user"];
[params setValue:#"sdsfddf23423" forKey:#"api_key"];
[params setValue:#"test#gmail.com" forKey:#"to"];
[params setValue:#"test user" forKey:#"toname"];
[params setValue:#"Test SendGrid" forKey:#"subject"];
[params setValue:#"Test SendGrid from iOS app" forKey:#"text"];
[params setValue:#"noreply#gmail.com" forKey:#"from"];
NSURL *url = [NSURL URLWithString:#"https://sendgrid.com/api"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: url];
NSMutableURLRequest *request = [client requestWithMethod:POST path:#"/mail.send.json" parameters:params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
DLog(#"Get latest product info response : %#", response);
NSLog(#"Success");
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure");
}];
[operation start];
}
Thanks in advance.
Update
I made some changes in code & now I can send the email successfully as below
-(void)sendEmailWithoutImage
{
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"subject":#"Test SendGrid",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
[[MyAPIClient sharedAPIClient] POST:#"mail.send.json" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"Success::responseObject : %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error::Mail response : %#", error);
}];
}
But when I try to send the image as attachment then it result in 400 bad request. So I think there is some error in my file uploading block. Here is my code
-(void)sendEmailWithImage
{
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"subject":#"Test SendGrid",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
[[MyAPIClient sharedAPIClient] POST:#"mail.send.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
UIImage *image = [UIImage imageNamed:#"redWine.png"];
NSData *imageToUpload = UIImagePNGRepresentation(image);
[formData appendPartWithFileData:imageToUpload name:#"files" fileName:[NSString stringWithFormat:#"%#",#"abc.png"] mimeType:#"image/png"];
}
success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"Success::responseObject : %#", responseObject);
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{
NSLog(#"Error::Mail response : %#", error);
}];
}
Can you anybody tell me whats going wrong while uploading the image ?
Thanks

Just modified your code a little. It looks like there was an issue with the parameters being sent and the URL path.
Also since you are already using AFNetworking to make your POST request, you can follow their docs and example on how to send a photo over here: http://cocoadocs.org/docsets/AFNetworking/2.0.1/
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"Test SendGrid":#"test",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
NSURL *url = [NSURL URLWithString:#"https://sendgrid.com/api/"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: url];
NSMutableURLRequest *request = [client requestWithMethod:#"POST" path:#"mail.send.json" parameters:parameters];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
// DLog(#"Get latest product info response : %#", response);
NSLog(#"Success: %#", response);
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
}];
[operation start];
Update**
Created a Sendgrid-ios library to make it easier to send an email and photo attachment.
//create Email Object
gridmail *msg = [gridmail user:#"username" andPass:#"password"];
//set parameters
msg.to = #"foo#bar.com";
msg.subject = #"subject goes here";
msg.from = #"me#bar.com";
msg.text = #"hello world";
msg.html = #"<h1>hello world!</h1>";
//Image attachment
[msg attachImage:self.photo];
//Send email through Web API Transport
[msg sendWithWeb];

Related

Can I use RestKit and Realm.io?

I want to use RestKit, but I already use Realm.io instead of CoreData.
Is it possible to use RestKit on top of Realm.io?
Sure you can. Once you get the object back from RestKit:
// GET a single Article from /articles/1234.json and map it into an object
// JSON looks like {"article": {"title": "My Article", "author": "Blake", "body": "Very cool!!"}}
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Article class]];
[mapping addAttributeMappingsFromArray:#[#"title", #"author", #"body"]];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // Anything in 2xx
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:#"/articles/:articleID" keyPath:#"article" statusCodes:statusCodes];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://restkit.org/articles/1234.json"]];
RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:#[responseDescriptor]];
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
Article *article = [result firstObject];
// I would put the Realm write here
NSLog(#"Mapped the article: %#", article);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Failed with error: %#", [error localizedDescription]);
}];
[operation start];
You will need to do two things:
Create your RealmArticle model (in this case) that inherits from RLMObject
Then you will just need to write to your realm
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[RealmArticle createInDefaultRealmWithObject:article];
[realm commitWriteTransaction];

how could i integrate via me social site into iphone app

hi i want to integrate Via Me social site into my iphone app,i googled but didn't find any samples.
The basic process is as follows:
Create a custom URL scheme for your app. Via Me will use this after the user has been authenticated, to return to your app. In my example, I created one called "robviame://"
Register your app at http://via.me/developers. This will give you a client id and a client secret:
When you want to authenticate the user, you call:
NSString *redirectUri = [[self redirectURI] stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:#"https://api.via.me/oauth/authorize/?client_id=%#&redirect_uri=%#&response_type=code", kClientID, redirectUri];
NSURL *url = [NSURL URLWithString:urlString];
[[UIApplication sharedApplication] openURL:url];
What that will do is fire up your web browser and give the user a chance to log on and grant permissions to your app. When user finishes that process, because you've defined your custom URL scheme, it will call the following method in your app delegate:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
// do whatever you want here to parse the code provided back to the app
}
for example, I'll call a handler for my Via Me response:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
ViaMeManager *viaMeManager = [ViaMeManager sharedManager];
if ([[url host] isEqualToString:viaMeManager.host])
{
[viaMeManager handleViaMeResponse:[self parseQueryString:[url query]]];
return YES;
}
return NO;
}
// convert the query string into a dictionary
- (NSDictionary *)parseQueryString:(NSString *)query
{
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSArray *queryParameters = [query componentsSeparatedByString:#"&"];
for (NSString *queryParameter in queryParameters) {
NSArray *elements = [queryParameter componentsSeparatedByString:#"="];
NSString *key = [elements[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *value = [elements[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
value = [[value componentsSeparatedByString:#"+"] componentsJoinedByString:#" "];
[dictionary setObject:value forKey:key];
}
return dictionary;
}
That handler might, for example, save the code and then request the access token:
- (void)handleViaMeResponse:(NSDictionary *)parameters
{
self.code = parameters[#"code"];
if (self.code)
{
// save the code
[[NSUserDefaults standardUserDefaults] setValue:self.code forKey:kViaMeUserDefaultKeyCode];
[[NSUserDefaults standardUserDefaults] synchronize];
// now let's authenticate the user and get an access key
[self requestToken];
}
else
{
NSLog(#"%s: parameters = %#", __FUNCTION__, parameters);
NSString *errorCode = parameters[#"error"];
if ([errorCode isEqualToString:#"access_denied"])
{
[[[UIAlertView alloc] initWithTitle:nil
message:#"Via Me functions will not be enabled because you did not authorize this app"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
else
{
[[[UIAlertView alloc] initWithTitle:nil
message:#"Unknown Via Me authorization error"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
}
}
and the code to retrieve the token might look like:
- (void)requestToken
{
NSURL *url = [NSURL URLWithString:#"https://api.via.me/oauth/access_token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSDictionary *paramsDictionary = #{#"client_id" : kClientID,
#"client_secret" : kClientSecret,
#"grant_type" : #"authorization_code",
#"redirect_uri" : [self redirectURI],
#"code" : self.code,
#"response_type" : #"token"
};
NSMutableArray *paramsArray = [NSMutableArray array];
[paramsDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
[paramsArray addObject:[NSString stringWithFormat:#"%#=%#", key, [obj stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding]]];
}];
NSData *paramsData = [[paramsArray componentsJoinedByString:#"&"] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:paramsData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error)
{
NSLog(#"%s: NSURLConnection error = %#", __FUNCTION__, error);
return;
}
NSError *parseError;
id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (parseError)
{
NSLog(#"%s: NSJSONSerialization error = %#", __FUNCTION__, parseError);
return;
}
self.accessToken = results[#"access_token"];
if (self.accessToken)
{
[[NSUserDefaults standardUserDefaults] setValue:self.accessToken forKey:kViaMeUserDefaultKeyAccessToken];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
}
Hopefully this will be enough to get you going. This is described in greater detail at the http://via.me/developers page.

UIImageJPEGRepresentation and crappy image

After trying I was able to upload an image taken from the camera to my webserver.
But what I do no understand is why the image quality is crappy, low resolution, very few colors. Is there a way to get a better quality ?
here is my code :
NSURL *url = [NSURL URLWithString:#"http://localhost"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation(image, 0.9);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:#"file" fileName:#"temp.jpeg" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
//[MBProgressHUD hideHUDForView:self.view animated:YES];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
//[MBProgressHUD hideHUDForView:self.view animated:YES];
if([operation.response statusCode] == 403)
{
NSLog(#"Upload Failed");
return;
}
NSLog(#"error: %#", [operation error]);
}];
[operation start];
thanks Regis
Sorry guys in order to work on my webserver I use realVnc. The set up of RealVnc was set to low resolution !!! I did change setup to have a better resolution and now the problem is solved!

How do I set basic authentication with RestKit 0.20.0?

I'm trying to use RestKit to call an endpoint that requires basic authentication.
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[JSNCategory class]];
[mapping addAttributeMappingsFromDictionary:#{
#"id": #"catId",
#"name": #"name"
}];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *responseDescriptor
= [RKResponseDescriptor responseDescriptorWithMapping:mapping
pathPattern:#"/api/v1/categories"
keyPath:nil
statusCodes:statusCodes];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:#"https://rest.example.com"]];
RKObjectRequestOperation *operation
= [[RKObjectRequestOperation alloc] initWithRequest:request
responseDescriptors:#[responseDescriptor]];
[operation setCompletionBlockWithSuccess:
^(RKObjectRequestOperation *operation, RKMappingResult *result) {
JSNCategory *cat = [result firstObject];
NSLog(#"Mapped the category: %#", cat);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Failed with error: %#", [error localizedDescription]);
}];
Using the objectmanager this would be something like:
NSURL* url = [[NSURL alloc]initWithString:#"http://rest.url.com"];
RKObjectManager* objectManager = [RKObjectManager managerWithBaseURL:url];
[objectManager.HTTPClient setAuthorizationHeaderWithUsername:#"username" password:#"password"];
Then, after setting the correct request/response you can use the objectmanager to do a get/post/etc:
[objectManager getObjectsAtPath:endpoint parameters:parameters success:
^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// do something
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
// do something
}
];

send parameter values and retrieve an xml file Xcode

In my current xcode project, I need to send parameter values to a url and need to retrieve an xml file based on the parameter values sent.
I tried the below code but it's not working:
(IBAction)myButtonClick:(id)sender
{
NSURL *oRequestURL =
[NSURL URLWithString:#"http://xyz .com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-06-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc"];
NSMutableURLRequest *oRequest = [[[NSMutableURLRequest alloc]init]autorelease];
[oRequest setHTTPMethod:#"POST"];
[oRequest setURL: oRequestURL];
NSMutableData *oHttpBody = [NSMutableData data];
[oHttpBody appendData:[#"This is HTTP Request body" dataUsingEncoding:NSUTF8StringEncoding]];
[oRequest setValue:[oHttpBody length] forHTTPHeaderField:#"Content-Length"];
NSError *oError = [[NSError alloc]init];
NSHTTPURLResponse *oResponseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:oRequest returningResponse:oResponseCode error:oError];
if ([oResponseCode statusCode]> 200) {
NSLog(#"Status code is greater than 200");
}
NSString *strResult=[[NSString alloc]initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(#"The result is %s",strResult);
}
I have searched many sites and books but could not find a solution.
Would be of great help if a link to a tutorial or some other useful resource can be provided. Appreciate your great help.
Thank You.
Hi,
I have found the solution. The code is as below. Hope it helps someone else:)
- (IBAction)myButtonPressed:(id)sender
{
NSString *urlAsString = #"http://api.abc.com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-09-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:#"2193141de2g7e2a34bb19bc3aa52b3b5" forHTTPHeaderField:#"X-XX-API-KEY"];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection
sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length]>0 &&
error == nil)
{
NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
}
else if ([data length]== 0 && error==nil) {
NSLog(#"Nothing was downloaded");
}
else if (error!= nil) {
NSLog(#"Error occured = %#", error);
}
}];
}

Resources