将.txt附加到MFMailComposeViewController

时间:2013-02-05 12:32:11

标签: ios objective-c xcode email-attachments mfmailcomposeviewcontroller

我有一个存储在Documents Folder中的.txt文件,我希望通过MFMailComposeViewController将其发送到-sendEmail方法体中的下一个代码:

NSData *txtData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dataBase" ofType:@"txt"]];
        [mail addAttachmentData:txtData mimeType:@"text/plain" fileName:[NSString stringWithFormat:@"dataBase.txt"]];

当邮件编辑器出现时,我可以在邮件正文中看到附件,但是我收到了没有附件的邮件。可能是.txt附件的MIME类型错误或者此代码有问题吗?

由于

2 个答案:

答案 0 :(得分:30)

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];        
        NSString *txtFilePath = [documentsDirectory stringByAppendingPathComponent:@"abc.txt"];
NSData *noteData = [NSData dataWithContentsOfFile:txtFilePath];
        MFMailComposeViewController *_mailController = [[MFMailComposeViewController alloc] init];
        [_mailController setSubject:[NSString stringWithFormat:@"ABC"]];
        [_mailController setMessageBody:_messageBody
                                 isHTML:NO];
        [_mailController setMailComposeDelegate:self];
        [_mailController addAttachmentData:noteData mimeType:@"text/plain" fileName:@"abc.txt"];

希望它有所帮助。

答案 1 :(得分:7)

在Swift 3中,您可以发送带有此附件的邮件

@IBAction func emailLogs(_ sender: Any) {
    let allPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = allPaths.first!
    let pathForLog = documentsDirectory.appending("/application.log")

    if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self;
        mail.setToRecipients(["recipient@email.com"])
        mail.setSubject("Application Logs")
        mail.setMessageBody("Please see attached", isHTML: true)

        if let fileData = NSData(contentsOfFile: pathForLog) {
            mail.addAttachmentData(fileData as Data, mimeType: "text/txt", fileName: "application.log")
        }

        self.present(mail, animated: true, completion: nil)
    }
}

然后关闭结果

上的作曲家控制器
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    controller.dismiss(animated: true, completion: nil)
}

确保订阅此代理

MFMailComposeViewControllerDelegate