如何将PDF文件附加到邮件并在iOS中发送邮件

时间:2014-06-20 10:48:54

标签: ios iphone

目前我正在开发费用管理应用程序,我想将PDF文件附加到邮件并将其发送到指定的电子邮件地址。因此,请指导我从哪里开始,以及如何开发它。

感谢。

MFMailComposeViewController *vc = [[MFMailComposeViewController alloc] init];
vc.mailComposeDelegate = self;

[vc setSubject:@"Monthly Expense Report"];
[vc addAttachmentData:pdfData mimeType:@"application/pdf" fileName:[NSString stringWithFormat:@"%@.pdf",[arrOfExpenseDate objectAtIndex:1]]];
if ([MFMailComposeViewController canSendMail])
{
    [self presentViewController:vc animated:YES completion:nil];
}

2 个答案:

答案 0 :(得分:4)

我为您创建了一个如何使用MFMailComposeViewController发送pdf附件的示例。以下是代码:

@interface ViewController () <MFMailComposeViewControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (IBAction)compseEmail:(id)sender
{
    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *vc = [[MFMailComposeViewController alloc] init];
        vc.mailComposeDelegate = self;

        [vc setSubject:@"Monthly Expense Report"];


        NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"ApacheInstallationSteps" ofType:@"pdf"];
        NSData *pdfData = [NSData dataWithContentsOfFile:pdfPath];
        [vc addAttachmentData:pdfData mimeType:@"application/pdf" fileName:@"ApacheInstallationSteps.pdf"];

        [self presentViewController:vc animated:YES completion:nil];
    }
    else
    {
        UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Alert!!!" message:@"Your device can't send emails." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

        [errorAlert show];
    }
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Result: canceled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Result: saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Result: sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Result: failed");
            break;
        default:
            NSLog(@"Result: not sent");
            break;
    }

    [self dismissViewControllerAnimated:YES completion:nil];
}

@end

确保添加MessageUI.framework。以下是输出。

enter image description here

答案 1 :(得分:0)

要使用MFMailComposeViewController以邮件方式发送pdf或任何其他信息,您必须使用:

[mc addAttachmentData:fileData mimeType:mimeType fileName:filename];

有关详细信息,请按照this教程。

您还可以下载本教程中给出的示例代码,以便更好地理解。

希望有所帮助。