我有一个谷歌应用程序脚本应用程序,它获取Gmail邮件附件,使用JDBC将其发布到数据库。然后在服务器上,PHP脚本获取数据并将其放入文件并将其附加到电子邮件中。
问题是电子邮件到达时文件已损坏
这是获取附件内容的谷歌应用程序脚本功能
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()发布到服务器,结果是相同的。显然,我在使用Base64_encode / decode做错了... 也许谷歌应用程序脚本:
Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);
创建一种不同于base6464decode所期望的base64格式?
P.S。 我也尝试过使用和不使用' str_pad'我仍然得到了相同的结果。
答案 0 :(得分:1)
我改变了:
Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);
为:
Utilities.base64Encode(GmailAttachments[i].getBytes());
并且有效