1

第一个错误

我使用此代码,但我不知道如何在 iOS 中使用 api Mailjet?将 API 密钥放在哪里私有,公共等...我检查了github mailjet,关于 API 的文档mailJet 没有成功。

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 放在哪里?在此处输入图像描述

编辑
第二个错误

新代码:

        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:\"contact@****.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];

新的错误信息: 在此处输入图像描述

有任何想法吗?

4

2 回答 2

1

我在 Mailjet 领导 API。

您的帖子中需要注意的几点:

  • 您的电话似乎缺少基本身份验证,有关设置它的更多详细信息,请参阅Postman 文档。您可以在此处获取您的 API 凭据
  • 您使用一段form-data Content-Type时间我们的 API 仅支持application/json作为输入格式。请参阅我们的API 指南,了解有关发送给我们的有效负载的更多详细信息
  • 您似乎没有在您提供的 Objective-C 代码中提供您的 API 凭据。与第一点相同,您可以从此处获取它们

我们不正式支持带有 Objective-C 或 Swift 的 iOS,对于给您带来的不便,我们深表歉意。

希望能帮助到你

感谢您选择 Mailjet 为您的电子邮件提供动力!

于 2017-05-19T16:39:21.630 回答
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:@"xxxx@xxxx.xxx" 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];

    }
于 2017-05-22T14:57:11.647 回答