2017-05-19 34 views
1

第一個錯誤如何以編程方式在iOS中使用API​​ MailJet發送附件的電子郵件?

我用這個代碼,但我不知道如何在iOS中使用API​​ Mailjet?在哪裏把API密鑰私人,公共等... 我檢查了郵件, mailjet,doc mailJet關於API沒有成功。

NSData *data = [NSData dataWithContentsOfFile:filePath]; 

NSLog(@"File Size: %lu",(unsigned long)[data length]); 

//set up request 
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init]; 
[request setURL:[NSURL URLWithString:@"https://api.mailjet.com/v3/send"]]; 
[request setHTTPMethod:@"POST"]; 

//required xtra info 
NSString *boundary = @"---------------------------14737809831466499882746641449"; 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; 
[request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

//body of the post 
NSMutableData *postbody = [NSMutableData data]; 
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"thefile\"; filename=\"recording\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postbody appendData:[@"Content-Type: application/octet-stream\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
[postbody appendData:data]; 
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

[request setHTTPBody:postbody]; 
NSURLConnection *apiConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

我做發送「手動」的測試,我有那個不好的答案。我必須把API KEY和SECRET KEY放在哪裏? enter image description here

編輯
第二個錯誤

新代碼:

 NSString *apiKey = @"*******************"; 
     NSString *secretKey = @"**************"; 
     NSString *mail = @"******@******.***"; 

     // Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept. 
     NSMutableDictionary* _params = [[NSMutableDictionary alloc] init]; 
     [_params setObject:@"1.0" forKey:@"ver"]; 
     [_params setObject:@"en" forKey:@"lan"]; 
     [_params setObject:apiKey forKey:@"apiKey"]; 
     [_params setObject:secretKey forKey:@"secretKey"]; 

     // the boundary string : a random string, that will not repeat in post data, to separate post data fields. 
     NSString *BoundaryConstant = @"----------***********"; 

     // string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ 
     NSString* FileParamConstant = @"file"; 

     // the server url to which the image (or the media) is uploaded. Use your server url here 
     NSURL* requestURL = [NSURL URLWithString:@"https://api.mailjet.com/v3/send/"]; 

     // create request 
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
     [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; 
     [request setHTTPShouldHandleCookies:NO]; 
     [request setTimeoutInterval:30]; 
     [request setHTTPMethod:@"POST"]; 

     //HTTP Basic Authentication 
     NSString *authenticationString = [NSString stringWithFormat:@"%@:%@", apiKey, secretKey]; 
     NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding]; 
     NSString *authenticationValue = [authenticationData base64Encoding]; 
     [request setValue:[NSString stringWithFormat:@"Basic %@", authenticationValue] forHTTPHeaderField:@"Authorization"]; 

     // set Content-Type in HTTP header 
     NSString *contentType = [NSString stringWithFormat:@"@"application/json"; boundary=%@", BoundaryConstant]; 
     [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; 
     [request addValue:apiKey forHTTPHeaderField:@"apiKey"] ; 
     [request addValue:secretKey forHTTPHeaderField:@"secretKey"] ; 

     // post bodyv 
     NSMutableData *body = [NSMutableData data]; 

     // add params (all params are strings) 
     for (NSString *param in _params) { 
      [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
      [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; 
      [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; 
     } 

     // add image data 
     UIImage *image = [UIImage imageWithContentsOfFile:filePath]; 
     NSData *imageData = UIImageJPEGRepresentation(image, 1.0); 
     if (imageData) { 
      [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
      [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; FromEmail:\"[email protected]****.fr\"; \"Text-part\":\"Dear\" ; Recipients:[{\"Email\":\"****@gmail.com\"}]; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
      [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
      [body appendData:imageData]; 
      [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
     } 

     [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 

     // setting the body of the post to the reqeust 
     [request setHTTPBody:body]; 

     // set the content-length 
     NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]]; 
     [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

     // set URL 
     [request setURL:requestURL]; 

     NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
     [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
      NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 
      NSLog(@"requestReply: %@, error: %@", requestReply, error); 
     }] resume]; 

新的錯誤消息: enter image description here

任何想法?

回答

1

下面是代碼:

- (void) sendToMail:(NSString *)mailingList 

{ 

    NSString *filePath = [[self documentsDirectory] stringByAppendingPathComponent:STATS_FILE]; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    mailingList = MAILING_LIST; 



    if ([fileManager fileExistsAtPath:filePath]) 

    { 

     // Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept. 

     NSMutableDictionary* _params = [[NSMutableDictionary alloc] init]; 

     [_params setObject:@"[email protected]" forKey:@"FromEmail"]; 

     [_params setObject:@"xxx xxx xxxx" forKey:@"FromName"]; 

     [_params setObject:@"xxx xxx xxx" forKey:@"Subject"]; 

     [_params setObject:@"xxx xxxx xxxx" forKey:@"Html-part"]; 

     //mail(s) treatment 

     NSUInteger numberOfOccurrences = [[mailingList componentsSeparatedByString:@";"] count] - 1; 

     NSArray *subStrings = [mailingList componentsSeparatedByString:@";"]; 

     NSMutableArray *mailsArr = [NSMutableArray new]; 



     for (int i=0; i<=numberOfOccurrences; i++) 

     { 

      NSString *mail = [subStrings objectAtIndex:i]; 

      if ([self validEmail:mail]) 

       [mailsArr addObject:@{@"Email":mail}]; 

     } 



     if ([mailsArr count] > 0) 

      [_params setObject:mailsArr forKey:@"Recipients"]; 



     //add any attachment file to JSON 

     NSData* data = [NSData dataWithContentsOfFile:filePath]; 

     if (data) 

     { 

      NSString *encodedString = [data base64EncodedStringWithOptions:0]; 

      NSArray *attachmentsArr = @[@{@"Content-type":@"text/plain", @"Filename":[NSString stringWithFormat:@"%@.db", [[[UIDevice currentDevice] identifierForVendor] UUIDString]], @"content":encodedString}]; 

      [_params setObject:attachmentsArr forKey:@"Attachments"]; 

     } 



     // the server url to which the image (or the media) is uploaded. Use your server url here 

     NSURL* requestURL = [NSURL URLWithString:@"https://api.mailjet.com/v3/send/"]; 



     // create request 

     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

     [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; 

     [request setHTTPShouldHandleCookies:NO]; 

     [request setTimeoutInterval:30]; 

     [request setHTTPMethod:@"POST"]; 



     //HTTP Basic Authentication 

     NSString *authenticationString = [NSString stringWithFormat:@"%@:%@", API_KEY, SECRET_KEY]; 

     NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding]; 

     NSString *authenticationValue = [authenticationData base64EncodedStringWithOptions:0]; 

     [request setValue:[NSString stringWithFormat:@"Basic %@", authenticationValue] forHTTPHeaderField:@"Authorization"]; 



     NSString *jsonRequest = [_params JSONRepresentation]; 

     NSLog(@"jsonRequest is %@", jsonRequest); 



     NSMutableData *requestData = [[jsonRequest dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; 

     [request setHTTPMethod:@"POST"]; 

     [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 

     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 



     // setting the body of the post to the request 

     [request setHTTPBody:requestData]; 



     // set the content-length 

     NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]]; 

     [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

     [request setURL:requestURL]; // set URL 



     NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

     [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

      NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 

#if DEBUG 

      NSLog(@"requestReply: %@, error: %@", requestReply, error); 

#endif 

      if (error == nil) 

      { 

       [self showAlertWithMessage:@"File sent!" withButton:@"Ok!"]; 

      } 

      else 

      { 

       [self showAlertWithMessage:@"Could not send file!" withButton:@"Ok!"]; 

      } 

     }] resume]; 

    } 
+1

謝謝,它完美的作品! – Claudio

1

我在Mailjet領先API。

幾件事情在您的文章指出:

  • 看來您的通話缺乏基本認證方式,請參見Postman documentation對即將設置的更多細節。您可以獲取您的API憑證here
  • 您使用form-dataContent-Type而我們的API僅支持application/json作爲輸入格式。請參閱我們的API guides關於有效載荷的更多詳細信息,請發送給我們
  • 您似乎沒有在您提供的objective-c代碼中提供您的API憑據。比第一點相同,可以從here

獲取他們我們不正式支持與Objective-C的或斯威夫特道歉給您帶來不便的iOS。

希望它可以幫助

感謝有選擇Mailjet供電您的電子郵件!

+0

我把基本認證方式,它的工作原理。但現在,我現在有一個不同的錯誤信息:至少400「至」所需的值。 (我編輯了我的門票信息代碼) – Claudio

+0

和謝謝您的投票:D – Claudio

+1

@Claudio,我的榮幸;)。您放入收件人的JSON似乎不是一個有效的JSON。它應該是'[{「Email」:「test @ gmail」}]'。問題不是單引號''',而是使用逗號','作爲鍵/值分隔符而不是分號':'。此外,我會建議使用自己的電子郵件地址進行測試,因爲[email protected]大多會導致反彈。 –

相關問題