Search code examples
iosxcodeemailnsmutableurlrequestmailjet

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


FIRST ERROR

I use this code but I don't know how to use the api Mailjet in iOS ? Where to put the API key private, the public etc... I check the github mailjet, the doc mailJet about the API without success.

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

I do tests with sending "manually", and I have that bad answer. Where I have to put the API KEY and the SECRET KEY ?enter image description here

EDIT
SECOND ERROR

New code :

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

New error message: enter image description here

Any ideas?


Solution

  • Here is the code:

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