I have a program I use to send mails using data in Google Sheet and typing the file name in the column in Sheet.
This was working fine as long as I had to send only one attachment.
However, now that I'm trying to send 2 attachments, I am not sure what change I need to make.
I looked at other responses - where you specify two variables instead of one - however in my case, its not definitive whether I'll mail 1 or 2 or 3 attachments, so I require a solution which can work with n number of files.
Attaching my current code for reference:
var attach = ws.getRange(lr, 17).getValue();
var file1 = DriveApp.getFilesByName(attach).next();
GmailApp.sendEmail('',
"" + sub + "",
'',
{htmlBody: htmlforemail,
bcc: emails.join(","),
attachments: file1
}
Issue and solution:
If I understand your situation correctly, you want to send multiple Drive files as attachments in an email. The names of these files can be found in a single cell in your spreadsheet, in a comma-separated string.
In this case, as you can see in the documentation, the attachments parameter requires an array of BlobSource to be provided, with each element in this array corresponding to each file.
Therefore, you should do the following:
Split the comma-separated string into an array with the file names (see split).
For each file name, look for the file in Drive (using getFilesByName and next, as you are already doing). You can use map to transform the file names array to a files array.
Provide the resulting array as attachments.
Code snippet:
var attach = ws.getRange(lr, 17).getValue().split(",");
var files = attach.map(fileName => DriveApp.getFilesByName(fileName).next());
GmailApp.sendEmail(recipient, subject, '', {
htmlBody: htmlforemail,
bcc: emails.join(","),
attachments: files
});
If you look at the documentation you will see that the attachments parameter expects to receive an array of files. So just push the files you need there and that's it.
Related
I want to update an existing spreadsheet in a drive folder but have trouble implementing the http request. I followed the documentation and was able to update a spreadsheet but the request body, which I tried to send in JSON, is always converted to CSV. This results in the distribution of the JSON parts into individual cells depending on present commas.
For instance, cell1= "{key1" and cell2= "value1" and so on. However, this prevents me from specifying the style of the sheet and values within the cells.
I found the possibility to send multipart request which, however, results in the same result. Now the first boundary string and the initial information until the first comma are included in the first cell and the rest ist divided according to existing commas.
What I want to do ist send an HTTP request with the body consisting of a JSON-File of specified information for the spreadsheet as described in the Sheets API of Google, but cannot find my current mistake. Even with mimetype set to "application/vnd.google-apps.spreadsheet" the json is always converted to csv.
mimetype "application/vnd.google-apps.spreadsheet"
If the file in question is an actuall google sheets file type. For example the mime type is "application/vnd.google-apps.spreadsheet". Then you should go though the google sheets api to update it. Other wise updating it though google drive you will need to load the file itself into a file stream and then upload it that way. You cant pick and choose what parts are uploaded with drive its all or nothing. Drive doesn't have the power to format things like cells and stuch it just uploads the raw file data.
Mimetype "text/plain"
If the file is in fact a csv file so the mime type is "text/plain" then you can update the text directly. by turning the text into a stream.
You have not said what language you are using so here is my sample for C#. The code is ripped from How to upload to Google Drive API from memory with C#
var uploadString = "Test";
var fileName = "ploadFileString.txt";
// Upload file Metadata
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = fileName,
Parents = new List<string>() { "1R_QjyKyvET838G6loFSRu27C-3ASMJJa" } // folder to upload the file to
};
var fsSource = new MemoryStream(Encoding.UTF8.GetBytes(uploadString ?? ""));
string uploadedFileId;
// Create a new file, with metadata and stream.
var request = service.Files.Create(fileMetadata, fsSource, "text/plain");
request.Fields = "*";
var results = await request.UploadAsync(CancellationToken.None);
if (results.Status == UploadStatus.Failed)
{
Console.WriteLine($"Error uploading file: {results.Exception.Message}");
}
// the file id of the new file we created
uploadedFileId = request.ResponseBody?.Id;
I am trying to download a file from Google Drive API v3. I have to do this by finding a file by name.
This is request url to get a file general information:
https://www.googleapis.com/drive/v3/files?q=name+%3D+'fileName.json'
and to download a file I have to use parameter alt=media.
It works but only when I am finding this file by id. I mean:
https://www.googleapis.com/drive/v3/files/3Gp-A4t6455kGGGIGX_gg63454354YD?alt=media
Anyone know how to download a file by name so using this?
https://www.googleapis.com/drive/v3/files?q=name+%3D+'fileName.json'
Answer:
Unfortunately it isn't possible to download a file from Google Drive using the file name in the URL itself.
Reasoning:
As can be seen in the image below, Google Drive supports multiple files having the same name. Each file, instead of being identified exclusively by its name, has a unique ID which tells it apart from other files. As it is possible to have, for example, three files all with the same name, making a request and only referring to the file name doesn't give enough information to identify exactly which file you want to download.
Workaround:
You can still use the filename to build the request, but first you need to make a list request to the Drive API so that you can obtain the specific file ID for the file you wish to download.
I'll assume the file you want to download is called fileName.json as in your question.
First, you'll want to make a list request to the server to obtain the initial file name. The scope you will need for this is:
https://www.googleapis.com/auth/drive.readonly
The request itself is as you placed in the question. Once you have obtained your token, you must make a GET request:
GET https://www.googleapis.com/drive/v3/files?q=name+%3D+'fileName.json'&key=[YOUR API KEY]
You must replace [YOUR API KEY] with your actual API key here. You can obtain a temporary one over at the OAuth Playground.
From this request you will get a JSON reponse of all the files in your Drive with the requested filename. This is an important point - if you only have one file with this filename, you have nothing to worry about and can continue from here. If more than one file exists then the JSON response will contain all these files and so extra code will need to be added here to retrieve the one you want.
Continuing on - the response you get back is of the following form:
{
"incompleteSearch": false,
"files": [
{
"mimeType": "application/json",
"kind": "drive#file",
"id": "<your-file-ID>",
"name": "fileName.json"
}
],
"kind": "drive#fileList"
}
From here, you can start to build your URL.
Building the download URL:
After retrieving the JSON response from the API, you need to extract the File ID to put into a URL. The following example is written in JavaScript/Google Apps Script, but can be built in whichever language suits your needs:
function buildTheUrl() {
var url = "https://www.googleapis.com/drive/v3/files";
var fileName = "fileName.json"
var apiKey = "your-api-key";
var parameters = "?q=name+%3D+'";
var requestUrl = url + parameters + fileName + "&key=" + apiKey;
var response = JSON.parse(UrlFetchApp.fetch(requestUrl).getContentText());
var fileId = response.files.id;
var downloadUrl = "https://www.googleapis.com/drive/v3/files/";
var urlParams = "?alt=media";
return downloadUrl + fileId + urlParams + "&key=" + apiKey;
}
This returns a string which is the download URL for the file. This is a Files: get request that can then be used to download the file in question.
References:
Google OAuth Playground
Google Drive API Files: list
Google Drive API Files: get
Google Apps Script: UrlFetchApp
w3schools: JSON objects
I had a script working with plaintext, but not having any luck with HTML formatting. with variables email, SUBJECT, and MESSAGE defined, I think this may work:
MailApp.sendEmail(email, SUBJECT, {htmlBody: MESSAGE});
The email sends as expected with the given subject, but the only information is "[object Object]" in plaintext.
I'm clearly messing up the syntax here, but I can't seem to reverse engineer how they did it in this tutorial.
Thanks!
var options = {};
options.name = "Some display name";
options.replyTo = "myEmail#domain.com";
options.htmlBody = "<b>An HTML message</b>";
MailApp.sendEmail("recipient#domain.com, title, "Plain text in case the receiver can't render HTML", options);
Personally I create an options Object that I pass to the sendEmail() method of the MailApp class. This way it's a bit easier to manage your extra parameters like HTML content.
However, you really should have read the documentation, which clearly states the multiple methods of sending an email. You want to send HTML content, so you need to use the method that takes the optional parameter. The optional parameter is an Object which has multiple key/value pairs that are used to further specify, well, options for the sent email.
I'm trying to understand how the Google API works server side in order to allow me to implement my own type of resumable upload. I understand that I can use the MediaFileUpload or MediaInMemoryUpload mechanism, but I am looking for something much more raw. For example, I want to deliberately upload 1k from a file, then later on (like days later), append another 1k of the file. Obviously not real figures here, but hopefully you get the idea. Well here is where I am with the code:
headers = {
'range': 'bytes=%d-%d' % (
offset,
offset + len(data)
)
}
body = {
'title': "MyFile.bin",
'description': "",
'modifiedDate': datetime.datetime.now().isoformat(),
'mimeType': 'application/octet-stream',
'parents': [{ 'id': parentId }]
}
res = http.request(
url, method="PUT", body=body, headers=headers
).execute()
So as you can see, it is clear where you specify the parameters for the file (file attributes) and the header specification for the request. But where do you specify the actual data stream to be uploaded in that request? Is it the case that I can just specify a media_body in the request?
You need to implement a multipart HTTP request which is explained on https://developers.google.com/drive/manage-uploads#multipart
I'd recommend you to use our JS client library and use the existing implementation on the API reference right under the JavaScript tab.
It is not possible and is not formally on Google's roadmap to introduce this functionality. The only way to append to a file is to update the entire file again from scratch.
I would like to do something like this:
var json = JSON.parse(urlFetch.getContentText());
var entry = json.feed.entry;
for(var i in entry){
if(userEmail == entry[i].getOwner()){
//Do Stuff
}
}
Assuming each entry here is a File in JSON retrieved from a call to DocsList feed, how can I hydrate it into an Apps Script File object so I can call normal File functions on it, like getOwner() or getFileType()?
Thanks!
You may analyze the each entry by looking on the json string. I beleive you are using Google Docs native API,
After looking on the documentation here, I can see
entry.author.email will give you author's email address.
Similarly, author's name: entry.author.name
You will not be having any method like getOwner() in that returned json.
Also, FYI, there is DocslList service in Apps Script, which has such methods