我有一个google应用程序脚本应用程序,它可以获取Gmail消息附件,并使用JDBC将其发布到DB。然后在服务器上,PHP脚本获取数据并放入文件中,并将其附加到电子邮件中。
问题是,当电子邮件到达时,文件已损坏。
下面是获取附件内容的google应用程序脚本函数
function getMessageAttachmentsArray(msg){
var GmailAttachments = msg.GmailMessage.getAttachments();
var validAttachments = [];
var attachmentNames = [];
if(GmailAttachments)
{
for(i in GmailAttachments)
{
var gName = GmailAttachments[i].getName();
attachmentNames.push(gName);
var mimeType = GmailAttachments[i].getContentType();
var size = GmailAttachments[i].getSize();
var content = Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);
var push = {"content":content,"mimeType":mimeType,"fileName":gName,"size":size,"id":""};
validAttachments.push(push);
}
}
return [validAttachments, attachmentNames];
}下面是从文件数据生成电子邮件的PHP代码:
require_once 'smtpmail/classes/class.phpmailer.php';
$mail = new PHPmailer(true);
$email = $argv[1];
$messageid = $argv[2];
$fax_number = $argv[3];
$attachments = array();
//get the attachments for this email
$Sql = "select * from user_attachments where email = '$email' and messageid like '$messageid%'";
$res = mysql_query($Sql);
while($row = mysql_fetch_array($res)){
$return['filename'] = $row['name'];
$return['mime'] = $row['mime_type'];
$content = base64_decode(str_pad(strtr($row['raw_data'], '-_', '+/'), strlen($row['raw_data']) % 4, '=', STR_PAD_RIGHT));
$temp_file = tempnam(sys_get_temp_dir(), 'Fax');
file_put_contents($temp_file, $content);
$return['file'] = $temp_file;
array_push($attachments, $return);
}
try{
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SetFrom("example@example.com", "example email");
$mail->Subject = '';
$mail->Body = ' '; //put in a blank body to avoid smtp error
$mail->AddAddress($email);
foreach($attachments as $file){
$mail->AddAttachment($file['file'], $file['filename'], 'base64' ,mime_content_type($file['file']));
}
if($mail->send()){
echo "email to $email sent successfully\n";
}else{
echo "error sending email to $email\n";
}
}catch(phpmailerException $e){
echo $e->errorMessage();
}catch(Exception $e){
echo $e->getMessage();
}当收到消息时,它会显示附件,但当下载时,我无法打开它们,并且有一条消息显示文件已损坏或文件扩展名与文件格式不匹配。
我做错什么了?
提前谢谢。
编辑:
我尝试用UrlFetchApp()发送到服务器,而不向DB发送附件,结果是一样的。显然,我在做一些Base64_encode /解码错误的事情.也许谷歌的应用程序脚本:
Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);创建不同的base64格式,而不是base64_decode所期望的?
附注:我也尝试过使用和不使用“str_pad”,而且我仍然得到了相同的结果。
发布于 2017-09-01 16:45:50
我改变了:
Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);至:
Utilities.base64Encode(GmailAttachments[i].getBytes());而且起作用了
https://stackoverflow.com/questions/45991569
复制相似问题