我正在通过PHP脚本发送电子邮件。这可以使用NSMutableURLRequest
正常工作,但我也希望将图像附加到电子邮件中。
这是我正在使用的代码:
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:@"http://example.com/email.php"]];
[request setHTTPMethod:@"POST"];
NSString*subject = [NSString stringWithFormat:@"Images from %@",[[UIDevice currentDevice] name]];
NSString*to = [[NSUserDefaults standardUserDefaults] objectForKey:@"PreferredPrinterEPrint"];
NSString *postString = [NSString stringWithFormat:@"to=%@&message=%@&subject=%@",to,@"hi",subject];
[request setValue:[NSString
stringWithFormat:@"%d", [postString length]]
forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
我看过一篇描述发送图片的文章here,但我不知道如何将两者结合起来。有人可以帮助我吗?
谢谢!
答案 0 :(得分:1)
ASIHTTPRequest 有一个名为ASIFormDataRequest的类,它使发布数据非常容易,并且包含使用单行附加文件的功能。我强烈推荐它。
答案 1 :(得分:0)
发送JPEG图像的示例:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://example.com/email.php"]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"Some string as you like";
NSString *value = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:value forHTTPHeaderField:@"Content-Type"];
NSString *subject = [NSString stringWithFormat:@"Images from %@", [[UIDevice currentDevice] name]];
NSString *to = [[NSUserDefaults standardUserDefaults] objectForKey:@"PreferredPrinterEPrint"];
NSData *fileData = [NSData dataWithContentsOfFile:<file path>]
NSMutableString *postDataString = @"".mutableCopy;
[postDataString appendFormat:@"--%@\r\n", boundary];
[postDataString appendFormat:@"Content-Disposition: form-data; name=\"to\"\r\n"];
[postDataString appendFormat:@"\r\n%@\r\n", to];
[postDataString appendFormat:@"--%@\r\n", boundary];
[postDataString appendFormat:@"Content-Disposition: form-data; name=\"message\"\r\n"];
[postDataString appendFormat:@"\r\n%@\r\n", @"hi"];
[postDataString appendFormat:@"--%@\r\n", boundary];
[postDataString appendFormat:@"Content-Disposition: form-data; name=\"subject\"\r\n"];
[postDataString appendFormat:@"\r\n%@\r\n", subject];
[postDataString appendFormat:@"--%@\r\n", boundary];
[postDataString appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", <file name>, <file name>];
[postDataString appendFormat:@"Content-Type: image/jpg\r\n"];
[postDataString appendFormat:@"Content-Transfer-Encoding: binary\r\n\r\n"];
NSMutableData *postData = [postDataString dataUsingEncoding:NSUTF8StringEncoding].mutableCopy;
[postData appendData:fileData];
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:[NSString stringWithFormat:@"%d", postDataString.length] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:postData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];