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

How can I send an email with attachement using the API MailJet in iOS programmatically?

第一个错误

我使用此代码,但我不知道如何在 iOS 中使用 api Mailjet?将 API 私钥放在哪里,public 等等... 我检查 github mailjet, the 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];

我通过发送 "manually" 进行测试,但我的答案很糟糕。我必须在哪里放置 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];

新错误信息:

有什么想法吗?

我在 Mailjet 领导 API。

您的 post 中需要注意的几点:

  • 您的通话似乎缺少基本身份验证,请参阅Postman documentation for more details on about to set it. You can fetch your API credentials here
  • 您使用 form-data Content-Type 而我们的 API 仅支持 application/json 作为输入格式。请参阅我们的 API guides 以了解有关发送给我们的有效负载的更多详细信息
  • 您似乎没有在您提供的 objective-c 代码中提供您的 API 凭据。与第一点相同,您可以从 here
  • 中获取它们

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

希望对您有所帮助

感谢您选择 Mailjet 来支持您的电子邮件!

代码如下:

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

    }