使用特定标签从电子邮件下载所有附件

时间:2017-08-07 17:59:50

标签: php gmail-api

我想编写一个脚本,使用Gmail API从所有标签为 Label_41 的电子邮件中下载所有附件。

我完成了https://developers.google.com/gmail/api/quickstart/php

的说明

使用API我预期的listUsersMessages(...)->getMessages()返回标签为 Label_41 的所有电子邮件。

$client = getClient();
$service = new Google_Service_Gmail($client);

$user = 'me';
$labels = array('labelIds' => array('Label_41'));
$messagesResponse = $service->users_messages->listUsersMessages($user, $labels);
$messages = $messagesResponse->getMessages();

foreach ($messages as $message) {
    echo 'Message with ID: ' . $message->getId();

    echo $message->getLabelIds();

    if($message->getLabelIds() == null) echo " (NO LABEL) ";

    echo  "\n";
}

但是,我在这里收到的所有电子邮件都没有分配标签,正如我的终端输出所示。我在这做错了什么?

enter image description here

2 个答案:

答案 0 :(得分:0)

问题是foreach循环中的$message对象几乎不包含任何数据。需要使用full参数启动消息对象。这是下载邮件的所有附件的最终代码,标签为 Label_41

client = getClient();
$service = new Google_Service_Gmail($client);

$user = 'me';
$optParams = [];
$optParams['labelIds'] = 'Label_41';

$messagesResponse = $service->users_messages->listUsersMessages($user, $optParams);
$messages = $messagesResponse->getMessages();

foreach ($messages as $message) {
    echo 'Message with ID: ' . $message->getId();

    $messageId = $message->getId();

    $optParamsGet = [];
    $optParamsGet['format'] = 'full'; // Display message in payload
    $message = $service->users_messages->get($user,$messageId,$optParamsGet);

    $messagePayload = $message->getPayload();
    $headers = $message->getPayload()->getHeaders();
    $parts = $message->getPayload()->getParts();

    $timestamp = ($message->internalDate) / 1000;

    $date = date('Y-m-d H-i-s', $timestamp);

    foreach ($parts as $part) {
      if($part->mimeType == 'application/pdf'){
          $attachmentId = $part['body']['attachmentId'];
      }
    }

    $data = $service->users_messages_attachments->get($user, $messageId, $attachmentId);
    $data = $data->data;
    $data = strtr($data, array('-' => '+', '_' => '/'));

    $filename = "Car2Go " . $date . ".pdf";

    if(!file_exists($filename)){
      $fh = fopen($filename, "w+");
      fwrite($fh, base64_decode($data));
      fclose($fh);
    }
    else{
      'File ' . $filename . 'already exists!';
    }

    echo  "\n";
}

答案 1 :(得分:0)

也许其他人会在寻找简单的解决方案。请参见下面可用作Google脚本的脚本代码(Java脚本,请参见此处的入门教程:https://script.google.com/home/start):

// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['sql','gz'];
//Name of the folder in google drive i which files will be put
var folderName = 'BACKUPS';
//Name of the label which will be applied after processing the mail message
var labelName = 'SavedToGDrive';



function GmailToDrive(){
  //build query to search emails
  var query = '';
  
  //uncomment to search by filetypes
  //filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+formattedDate+
  //for(var i in fileTypesToExtract){
  //	query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
  //}
  //query = 'in:inbox has:nouserlabels ' + query;
  
  //search by label
  query = 'label:backups-real-estate-backup';
  //exclude already downloaded mails, so you can repeat running this script 
  if timeout happened
  query = query + ' AND NOT label:savedtogdrive';
  
  var threads = GmailApp.search(query);
  var label = getGmailLabel_(labelName);
  var parentFolder;
  if(threads.length > 0){
    parentFolder = getFolder_(folderName);
  }
  var root = DriveApp.getRootFolder();
  for(var i in threads){
    var mesgs = threads[i].getMessages();
	for(var j in mesgs){
      //get attachments
      var attachments = mesgs[j].getAttachments();
      for(var k in attachments){
        var attachment = attachments[k];
        var isDefinedType = checkIfDefinedType_(attachment);
    	if(!isDefinedType) continue;
    	var attachmentBlob = attachment.copyBlob();
        var file = DriveApp.createFile(attachmentBlob);
        parentFolder.addFile(file);
        root.removeFile(file);
      }
	}
	threads[i].addLabel(label);
  }
}

//This function will get the parent folder in Google drive
function getFolder_(folderName){
  var folder;
  var fi = DriveApp.getFoldersByName(folderName);
  if(fi.hasNext()){
    folder = fi.next();
  }
  else{
    folder = DriveApp.createFolder(folderName);
  }
  return folder;
}

//getDate n days back
// n must be integer
function getDateNDaysBack_(n){
  n = parseInt(n);
  var date = new Date();
  date.setDate(date.getDate() - n);
  return Utilities.formatDate(date, Session.getScriptTimeZone(), 'yyyy/MM/dd');
}

function getGmailLabel_(name){
  var label = GmailApp.getUserLabelByName(name);
  if(!label){
	label = GmailApp.createLabel(name);
  }
  return label;
}

//this function will check for filextension type.
// and return boolean
function checkIfDefinedType_(attachment){
  var fileName = attachment.getName();
  var temp = fileName.split('.');
  var fileExtension = temp[temp.length-1].toLowerCase();
  if(fileTypesToExtract.indexOf(fileExtension) !== -1) return true;
  else return false;
}

谢谢。