使用phonegap开发android应用需要有发送邮件并且带附件的功能,使用的时EmailComposer插件,因为这个插件可以在android和ios上都可以使用。
但是在使用EmailComposer插件的时候会出现很多开发过程中的问题,其中一个就是模拟器上没有弹出邮件发送界面,导致我一直以为该插件有问题,其实在真机上是没有问题的。
第二个就是附件在打开的邮件发送界面中一直没有显示,网上找了很多资料都不知道问题所在,最后自己摸索才发现其实附件的路径出问题了。从phonegap的fileEntry.fullPath里获取的文件全路径是:file:///sdcard/YSSSFile/customer.xls,而EmailComposer插件需要的附件路径是这样的:/sdcard/YSSSFile/customer.xls,因此要对fileEntry.fullPath里获取的文件全路径进行字符串截取处理,以下是找到附件的全路径并使用EmailComposer插件发送邮件加上附件的代码:
//等待加载PhoneGap
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap加载完毕
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
//获取newFile目录,如果不存在则创建该目录
function gotFS(fileSystem) {
newFile = fileSystem.root.getDirectory("YSSSFile", {create : true,exclusive : false}, writerFile, fail);
}
//获取newFile目录下面的dataFile.txt文件,如果不存在则创建此文件
function writerFile(newFile) {
newFile.getFile("customer.xls", {create : true,exclusive : false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
console.log("customer.xls's full path:"+fileEntry.fullPath);
alert("customer.xls's full path:"+fileEntry.fullPath);
var sender = [];
sender.push("lihaj@fenhon.com");
sender.push("www@51shuaige.com");
var _localFile = fileEntry.fullPath.slice(7);
//var _localFile = "file:///sdcard/YSSSFile/customer.xls";
var files = [];
files.push(_localFile);
alert(_localFile);
window.plugins.emailComposer.showEmailComposerWithCallback(
function(result){
console.log(result);
alert("emailComposer_send_email_result:"+result);
},"YSSS email","YSSS content",sender,
[],[],false,files);
console.log("sendemail_file_after");
alert("sendemail_file_after");
//fileEntry.createWriter(gotFileWriter, fail);
}
function fail(error) {
alert("Failed to retrieve file:" + error.code);
console.log("Failed to retrieve file:" + error.code);
//alert("Failed to retrieve file:" + error.code);
}
关键是要加上这一句:var _localFile = fileEntry.fullPath.slice(7);
把file://这几个字符串去掉了。只剩下/sdcard/YSSSFile/customer.xls 这个文件路径,和linux上的一样,其实android就是linux嘛。这样附件就能在邮件发送的界面显示出来了。