如何以编程方式在iOS中使用API​​ MailJet发送附件的电子邮件?

问题描述:

第一个错误如何以编程方式在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

任何想法?

下面是代码:

- (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

我在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]大多会导致反弹。 –