以编程方式通过电子邮件发送iphone附件 [英] Send an iphone attachment through email programmatically
问题描述
[self exportData];
if([MFMailComposeViewController canSendMail])
{
NSString * filePath = [[NSBundle mainBundle] pathForResource:@expensesofType:@csv];
NSData * myData = [NSData dataWithContentsOfFile:filePath];
MFMailComposeViewController * mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:@myConsultant的车费];
NSString * emailBody = @;
[mailer setMessageBody:emailBody isHTML:NO];
[mailer addAttachmentData:myData mimeType:@text / plainfileName:@expenses];
[self presentModalViewController:mailer animated:YES];
[邮件发布];
}
else
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@Failure
message:@您的设备不支持作曲家
委托:nil
cancelButtonTitle:@OK
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
- (void)mailComposeController :( MFMailComposeViewController *)控制器didFinishWithResult:(MFMailComposeResult)结果错误:(NSError *)错误
{
switch )
{
案例MFMailComposeResultCancelled:
NSLog(@取消邮件:您取消了操作,没有电子邮件消息已排队。
break;
案例MFMailComposeResultSaved:
NSLog(@保存邮件:您将电子邮件保存在草稿文件夹中);
break;
case MFMailComposeResultSent:
NSLog(@邮件发送:电子邮件在发件箱中排队,准备发送);
break;
case MFMailComposeResultFailed:
NSLog(@邮件失败:电子邮件未保存或排队,可能是由于错误。
break;
default:
NSLog(@Mail not sent。);
break;
}
//删除邮件视图
[self dismissModalViewControllerAnimated:YES];
正在成功创建 - 我检查了模拟器文件。
- (void)exportData
{
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString * documentsDir = [paths objectAtIndex:0];
NSString * root = [documentsDir stringByAppendingPathComponent:@expenses.csv];
NSString * temp = @日期,目的,开始里程表,最终里程表,总驱动,费用; (int i = 0; i< expenses.count; i ++){
VehicleExpense * tempExpense = [expenses objectAtIndex:i];
temp = [temp stringByAppendingString:tempExpense.date];
temp = [temp stringByAppendingString:@,];
temp = [temp stringByAppendingString:tempExpense.purpose];
temp = [temp stringByAppendingString:@,];
temp = [temp stringByAppendingString:[NSString stringWithFormat:@%。02f,tempExpense.start_mile]];
temp = [temp stringByAppendingString:@,];
temp = [temp stringByAppendingString:[NSString stringWithFormat:@%。02f,tempExpense.end_mile]];
temp = [temp stringByAppendingString:@,];
temp = [temp stringByAppendingString:[NSString stringWithFormat:@%。02f,tempExpense.distance]];
temp = [temp stringByAppendingString:@,];
temp = [temp stringByAppendingString:[NSString stringWithFormat:@%。02f,tempExpense.fees]];
temp = [temp stringByAppendingString:@,];
}
[temp writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(@在这里出口数据---%@,documentsDir);
}
b $ b [mailer addAttachmentData:myData mimeType:@text / csvfileName:@expenses.csv];
编辑:
这是我在我的应用程序中使用的代码:
- (IBAction)ExportData:(id)sender
{
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * filePath = [documentsDirectory stringByAppendingPathComponent:kExportFileName];
self.timeRecords = [[NSMutableArray alloc] init]; (int i = 0; i< [self.selectedTimeEntries count]; i ++)
for(int j = 0; j [[self.selectedTimeEntries objectAtIndex:i] count]; j ++)
if([[self.selectedTimeEntries objectAtIndex:i] objectAtIndex:j] == [NSNumber numberWithBool:YES])
[self.timeRecords addObject:[self.uniqueArray objectAtIndex:i] forIndex :J]];
if(!([self.timeRecords count]!= 0))
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@没有时间条目选择!消息:@请至少选择一个时间条目,然后继续委托:self cancelButtonTitle:@OKotherButtonTitles:nil];
[alert show];
[alert release];
return;
}
NSMutableString * csvLine;
NSError * err = nil;
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@yyyy-MM-dd];
NSString * dateString = nil;
NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPositiveFormat:@### 0。##];
NSString * formattedNumberString = nil;
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
[[NSFileManager defaultManager] createFileAtPath:filePath内容:nil属性:nil];
}
for(timeEntries * timeEntry in self.timeRecords){
csvLine = [NSMutableString stringWithString:timeEntry.client];
[csvLine appendString:@,];
[csvLine appendString:timeEntry.category];
[csvLine appendString:@,];
[csvLine appendString:timeEntry.task];
[csvLine appendString:@,];
dateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeEntry.date]];
[csvLine appendString:dateString];
[csvLine appendString:@,];
formattedNumberString = [numberFormatter stringFromNumber:timeEntry.duration];
[csvLine appendString:formattedNumberString];
[csvLine appendString:@,];
[csvLine appendString:timeEntry.description];
[csvLine appendString:@\\\
];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSString * oldFile = [[NSString alloc] initWithContentsOfFile:filePath];
[csvLine insertString:oldFile atIndex:0];
BOOL success = [csvLine writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:& err];
if(success){
}
[oldFile release];
}
}
如果(!appDelegate.shouldSendCSV){
self.csvText = csvLine;
}
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
[self emailExport:filePath];
}
self.selectedTimeEntries = nil;
self.navigationController.toolbarHidden = NO;
- (void)emailExport:(NSString *)filePath
{
NSLog(@应发送CSV =%@,[ NSNumber numberWithBool:appDelegate.shouldSendCSV]);
MFMailComposeViewController * picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
//设置邮件主题
[picker setSubject:@My Billed Time Export];
//添加电子邮件地址
//注意三个部分:到cc和bcc
NSString * valueForEmail = [[NSUserDefaults standardUserDefaults] stringForKey:@ emailEntry];
NSString * valueForCCEmail = [[NSUserDefaults standardUserDefaults] stringForKey:@ccEmailEntry];
if(valueForEmail == nil || [valueForEmail isEqualToString:@]
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@请在发送之前设置一个电子邮件地址一次入场!消息:@您可以稍后从应用程序的设置菜单中更改此地址!委托:self cancelButtonTitle:@OKotherButtonTitles:nil];
[alert show];
[alert release];
return;
}
else {
[选择器setToRecipients:[NSArray arrayWithObjects:valueForEmail,nil]];
if(valueForCCEmail!= nil ||![valueForCCEmail isEqualToString:@]
{
[选择器setCcRecipients:[NSArray arrayWithObjects:valueForCCEmail,零]];
}
//填写电子邮件正文文本
NSString * emailBody = @我的计费时间导出文件;
//这不是HTML格式的电子邮件
[picker setMessageBody:emailBody isHTML:NO];
if(appDelegate.shouldSendCSV){
//从文件
创建NSData对象NSData * exportFileData = [NSData dataWithContentsOfFile:filePath];
//将图像数据附加到电子邮件
[picker addAttachmentData:exportFileData mimeType:@text / csvfileName:@MyFile.csv];
} else {
[picker setMessageBody:self.csvText isHTML:NO];
}
//显示电子邮件视图
[self presentModalViewController:picker animated:YES];
//发布选择器
[选择器释放];
}
I am writing an iPhone app that requires that I send an e-mail attachment programmatically. The attachment is a csv file, that I create through the code. I then attach the file to the email, and the attachment shows up on the phone. When I send the email to myself, however, the attachment doesn't appear in the e-mail. Here is the code I'm using.
[self exportData];
if ([MFMailComposeViewController canSendMail])
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"expenses" ofType:@"csv"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:@"Vehicle Expenses from myConsultant"];
NSString *emailBody = @"";
[mailer setMessageBody:emailBody isHTML:NO];
[mailer addAttachmentData:myData mimeType:@"text/plain" fileName:@"expenses"];
[self presentModalViewController:mailer animated:YES];
[mailer release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
message:@"Your device doesn't support the composer sheet"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(@"Mail cancelled: you cancelled the operation and no email message was queued.");
break;
case MFMailComposeResultSaved:
NSLog(@"Mail saved: you saved the email message in the drafts folder.");
break;
case MFMailComposeResultSent:
NSLog(@"Mail send: the email message is queued in the outbox. It is ready to send.");
break;
case MFMailComposeResultFailed:
NSLog(@"Mail failed: the email message was not saved or queued, possibly due to an error.");
break;
default:
NSLog(@"Mail not sent.");
break;
}
// Remove the mail view
[self dismissModalViewControllerAnimated:YES];
The is being successfully created- I checked in the simulator files.
- (void) exportData
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *root = [documentsDir stringByAppendingPathComponent:@"expenses.csv"];
NSString *temp=@"Date,Purpose,Start Odometer,End Odometer, Total Driven, Fees, ";
for(int i = 0; i < expenses.count; i++){
VehicleExpense *tempExpense = [expenses objectAtIndex:i];
temp = [temp stringByAppendingString:tempExpense.date];
temp = [temp stringByAppendingString:@", "];
temp = [temp stringByAppendingString:tempExpense.purpose];
temp = [temp stringByAppendingString:@", "];
temp = [temp stringByAppendingString:[NSString stringWithFormat: @"%.02f",tempExpense.start_mile]];
temp = [temp stringByAppendingString:@", "];
temp = [temp stringByAppendingString:[NSString stringWithFormat: @"%.02f",tempExpense.end_mile]];
temp = [temp stringByAppendingString:@", "];
temp = [temp stringByAppendingString:[NSString stringWithFormat: @"%.02f",tempExpense.distance]];
temp = [temp stringByAppendingString:@", "];
temp = [temp stringByAppendingString:[NSString stringWithFormat: @"%.02f",tempExpense.fees]];
temp = [temp stringByAppendingString:@", "];
}
[temp writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"got here in export data--- %@", documentsDir);
}
try
[mailer addAttachmentData:myData mimeType:@"text/csv" fileName:@"expenses.csv"];
Edit: This is the code I'm using in my app:
- (IBAction) ExportData:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:kExportFileName];
self.timeRecords = [[NSMutableArray alloc] init];
for (int i=0; i< [self.selectedTimeEntries count]; i++)
for (int j=0; j<[[self.selectedTimeEntries objectAtIndex:i] count]; j++)
if ([[self.selectedTimeEntries objectAtIndex:i] objectAtIndex:j] == [NSNumber numberWithBool:YES])
[self.timeRecords addObject:[self timeEntriesForDay:[self.uniqueArray objectAtIndex:i] forIndex:j]];
if( !([self.timeRecords count]!=0))
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"There are no time entries selected!" message:@"Please select at least one time entry before proceeding" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
NSMutableString *csvLine;
NSError *err = nil;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *dateString = nil;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPositiveFormat:@"###0.##"];
NSString *formattedNumberString = nil;
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}
for (timeEntries *timeEntry in self.timeRecords) {
csvLine = [NSMutableString stringWithString:timeEntry.client];
[csvLine appendString:@","];
[csvLine appendString:timeEntry.category];
[csvLine appendString:@","];
[csvLine appendString:timeEntry.task];
[csvLine appendString:@","];
dateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeEntry.date]];
[csvLine appendString:dateString];
[csvLine appendString:@","];
formattedNumberString = [numberFormatter stringFromNumber:timeEntry.duration];
[csvLine appendString:formattedNumberString];
[csvLine appendString:@","];
[csvLine appendString:timeEntry.description];
[csvLine appendString:@"\n"];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSString *oldFile = [[NSString alloc] initWithContentsOfFile:filePath];
[csvLine insertString:oldFile atIndex:0];
BOOL success =[csvLine writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:&err];
if(success){
}
[oldFile release];
}
}
if (!appDelegate.shouldSendCSV) {
self.csvText = csvLine;
}
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
[self emailExport:filePath];
}
self.selectedTimeEntries =nil;
self.navigationController.toolbarHidden = NO;
}
- (void)emailExport:(NSString *)filePath
{
NSLog(@"Should send CSV = %@", [NSNumber numberWithBool:appDelegate.shouldSendCSV]);
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
// Set the subject of email
[picker setSubject:@"My Billed Time Export"];
// Add email addresses
// Notice three sections: "to" "cc" and "bcc"
NSString *valueForEmail = [[NSUserDefaults standardUserDefaults] stringForKey:@"emailEntry"];
NSString *valueForCCEmail = [[NSUserDefaults standardUserDefaults] stringForKey:@"ccEmailEntry"];
if( valueForEmail == nil || [valueForEmail isEqualToString:@""])
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Please set an email address before sending a time entry!" message:@"You can change this address later from the settings menu of the application!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
else {
[picker setToRecipients:[NSArray arrayWithObjects:valueForEmail, nil]];
}
if(valueForCCEmail != nil || ![valueForCCEmail isEqualToString:@""])
{
[picker setCcRecipients:[NSArray arrayWithObjects:valueForCCEmail, nil]];
}
// Fill out the email body text
NSString *emailBody = @"My Billed Time Export File.";
// This is not an HTML formatted email
[picker setMessageBody:emailBody isHTML:NO];
if (appDelegate.shouldSendCSV) {
// Create NSData object from file
NSData *exportFileData = [NSData dataWithContentsOfFile:filePath];
// Attach image data to the email
[picker addAttachmentData:exportFileData mimeType:@"text/csv" fileName:@"MyFile.csv"];
} else {
[picker setMessageBody:self.csvText isHTML:NO];
}
// Show email view
[self presentModalViewController:picker animated:YES];
// Release picker
[picker release];
}
这篇关于以编程方式通过电子邮件发送iphone附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!