How to add a attachment into GMail per script - scripting

I have created the following script to add a file to a GMail:
function mySendEMail(NIDMail) {
var mySubject = "This is only a Test";
var myURL = DriveApp.getFileById(NIDMail).getUrl();
var myBody = "Hello World,\n\n";
myBody = myBody + "dddddddddddd\n";
var file = DriveApp.getFileById(NIDMail);
MailApp.sendEmail("xxxxx#googlemail.com", mySubject, myBody, {
attachments: [file.getAs(MimeType.PDF)],
})
}
With this script I add the file per PDF, but how I can add a attachment per Link to GoogleDrive (like with the GDrive-Symbol)?
Greetings

I believe you are trying to replicate the behavior of "Insert file using Drive" in the email composition where the attachment is the link to the file in the Google Drive and not the downloadable version of the file.
This feature is not yet available to the attachments of sendEmail but you can use the htmlBody (documentation) as parameter to sendEmail and add a clickable image or text as element. This will automatically includes a Drive URL (similar to 'Insert file using Drive') in the attachments section of email.
Sample Email:
Here's the code snippet I used to produce the sample email above:
function mySendEMail() {
var NIDMail = "xxxxxxxxxx";
var mySubject = "This is only a Test";
var myURL = DriveApp.getFileById(NIDMail).getUrl();
var myBody = "Hello World,\n\n";
var gdriveLogo = "https://firebasestorage.googleapis.com/v0/b/drive-assets.google.com.a.appspot.com/o/Asset%20-%20Drive%20Lockup.png?alt=media"
var html_body = "<p>This is a test email</p>"
+ "<br>"
+ "<p>(Test Document)</p>"
+ "<br>"
+ "<a href='" + myURL + "'>"
+ "<img src='" + gdriveLogo + "' width='130' height='50'>"
+ "</a>";
MailApp.sendEmail({
to: "xxxxxemailxxxxxx",
subject: mySubject,
htmlBody: html_body
});
}

Related

Convert PDF from Google Drive to Image and send to Telegram via Bot

Currently the step by step I use is as follows:
First step -> Create a PDF of the Page Jogos na TV from my spreadsheet:
function CreatePDF() {
var ss = SpreadsheetApp.getActive();
SpreadsheetApp.flush();
var theurl = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/' +
'ID CODE TO SPREADSHEET' +
'/export?format=pdf' +
'&size=0' +
'&portrait=true' +
'&fitw=true' +
'&top_margin=0' +
'&bottom_margin=0' +
'&left_margin=0' +
'&right_margin=0' +
'&sheetnames=false&printtitle=false' +
'&pagenum=false' +
'&gridlines=false' +
'&fzr=FALSE' +
'&gid=' +
'ID CODE TO SPREADSHEET PAGE';
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdfBlob = docurl.getBlob();
//...get token and Blob (do not create the file);
var fileName = ss.getSheetByName("Jogos na TV").getRange("A1").getValue();
//Access or create the 'PDF' folder;
var folder;
var folders = DriveApp.getFoldersByName("PDF");
if(folders.hasNext()) {
folder = folders.next();
}else {
folder = DriveApp.createFolder("PDF");
}
//Remove duplicate file with the same name;
var existing = folder.getFilesByName(fileName);
if(existing.hasNext()) {
var duplicate = existing.next();
if (duplicate.getOwner().getEmail() == Session.getActiveUser().getEmail()) {
var durl = 'https://www.googleapis.com/drive/v3/files/'+duplicate.getId();
var dres = UrlFetchApp.fetch(durl,{
method: 'delete',
muteHttpExceptions: true,
headers: {'Authorization': 'Bearer '+token}
});
var status = dres.getResponseCode();
if (status >=400) {
} else if (status == 204) {
folder.createFile(pdfBlob.setName(fileName));
}
}
} else {
folder.createFile(pdfBlob.setName(fileName));
}
}
Second Step -> Manually copy the PDF link created in Google Drive
Step Three -> I send the text with the PDF minature to my group on Telegram:
function EnviarTelegram(botSecret, chatId, photoUrl, caption) {
var response = UrlFetchApp.fetch("https://api.telegram.org/bot" + botSecret + "/sendPhoto?caption=" + encodeURIComponent(caption) + "&photo=" + encodeURIComponent(photoUrl) + "&chat_id=" + chatId + "&parse_mode=HTML");
}
The current formula for sending to Telegram via spreadsheet:
=EnviarTelegram("botSecret","chatId","Url to PDF","Programação de jogos na TV
"&TEXT('Jogos Hoje'!B1,"DD/MM/YYYY")&" e "&TEXT('Jogos Amanhã'!B1,"DD/MM/YYYY"))
The thumbnail created for the PDF is cut so the image sent to Telegram is also cut and the spreadsheets cannot be saved as an image, just document or PDF.
Is there any way to automatically convert PDF to image and be able to send to Telegram?
Issue and workarounds:
Unfortunately, there are no methods for directly converting the PDF format to the image data in the methods of Google Apps Script. So, in this case, I thought that it is required to use the workarounds for achieving your goal.
Workaround 1:
In this workaround, the external API is used. When you want to directly convert the PDF data to an image data, how about using an external API? Ref
You can see the sample script for this at this thread.
Workaround 2:
In this workaround, the range of sheet is exported as an image. When I saw your Spreadsheet, it seems that the data range of a sheet in Google Spreadsheet is exported as a PDF data. From this situation, as the other workaround, how about converting the range of Spreadsheet to an image?
You can see the sample script for this at this thread.
Workaround 3:
In this workaround, the PDF data is sent with sendDocument. Ref In this case, it seems that the data is required to be sent as multipart/form-data. The sample script is as follows.
Sample script:
var url = "https://api.telegram.org/bot" + botSecret + "/sendDocument?chat_id=" + chatId;
var blob = DriveApp.getFileById("### file ID of PDF file ###").getBlob();
var res = UrlFetchApp.fetch(url, {method: "post", payload: {document: blob}});
console.log(res.getContentText())
References:
PDF to PNG API
sendDocument
Related threads.
Convert a gdoc into image
How to copy a range from a spreadsheet as an image to Google Slides?

Saving one sheet as PDF in Google Drive (for all Users)

I made an Excel Sheet in Google Drive to be used by 15 Peoples. The function is that the macro should create a PDF from the Sheet and send it to peoples as Mail. But I want to make a copy as PDF in Google Drive where can I see all of this persons permissions to see all of the sent Mails.
I must say that I am a beginner for this macro thing, I tried 2 codes but I always get the same Error.
function TEST2()
{
var Datum = Utilities.formatDate(new Date(), "GMT+2", "dd.MM.YYYY HH:mm");
var as = SpreadsheetApp.getActive();
var newas = SpreadsheetApp.create("XX");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("XX");
sheet = as.getSheetByName("XX");
sheet.copyTo(newas);
newas.getSheetByName('XX');
newas.deleteActiveSheet();
var pdf = DriveApp.getFileById(newas.getId()).getAs('application/pdf').getBytes();
var anhang = {fileName:("XX Order" + Datum + ".pdf"),content:pdf,mimeType:'application/pdf'};
var folderID = "TEST FOLDER";
var folder = DriveApp.getFolderById(folderID);
var newFile = DriveApp.createFile(folder);
newFile;
MailApp.sendEmail(
{
to: "Mail Adress",
subject: "XX Order " + Datum,
htmlBody: "XX - Order ",
attachments: anhang
})
SpreadsheetApp.getUi().alert('Mail wurde versendet ' + Datum)
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
I always get the same Error message. That the script cannot find a document with this ID.
Ok i found the solution :)
var folderID = "XXX BESTELLUNG";
var folderID2 = "XXX Bestellung";
var folder = DriveApp.getFoldersByName(folderID);
var theblob = newas.getBlob().getAs('application/pdf').setName('XXX Bestellung ' + Datum);
var newFile = folder.next().getFoldersByName(folderID2).next().createFile(theblob);
when i change the code in this case, i get the solution whicht i want :)

PDF margins - Google Script

I have the basic script working fine, it does exactly what I want it to do. It takes the Google Sheet turns it into a PDF and emails me the PDF.
My question is how can I adjust the margins on the PDF, I need to set the PDF to fit page. I can't just resize the sheet because it throws the spacing off.
/* Email Google Spreadsheet as PDF */
function PDF() {
// Send the PDF of the spreadsheet to this email address
var email = "gmail.com";
// Get the currently active spreadsheet URL (link)
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com');
// Subject of email message
var subject = "PAR - " + ss.getRange("A6:A6").getValue() +" - "+ ss.getRange("A5:A5").getValue();
// Email Body can be HTML too
var body = "Name - " + ss.getRange("A6:A6").getValue() +" - "+ ss.getRange("A5:A5").getValue();
var blob = DriveApp.getFileById(ss.getId()).getAs("application/pdf");
blob.setName("Name - " + ss.getRange("A6:A6").getValue() +" - "+ ss.getRange("A5:A5").getValue() + ".pdf");
// If allowed to send emails, send the email with the PDF attachment
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments:[blob]
});
}
I've seen script like this but cant figure out how to get it to work on my script.
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=false' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
I've got the same issue, I also want to remove the margins. It is is any help, here is my working script, which includes the part you are mentioning above.
But I don't see a parameter where you can adjust the margins...
function CreaPDF() {
var report = SpreadsheetApp.getActive();
var pdfName = "ReportXXX";
var sheetName = "Sheet1";
var sourceSheet = report.getSheetByName(sheetName);
SpreadsheetApp.getActiveSpreadsheet().toast('Creating the PDF');
// export url
var url = 'https://docs.google.com/spreadsheets/d/'+report.getId()+'/export?exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=A4' // paper size legal / letter / A4
+ '&portrait=false' // orientation, false for landscape
+ '&fitw=true' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='+sourceSheet.getSheetId(); // the sheet's Id
var token = ScriptApp.getOAuthToken();
// request export url
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var theBlob = response.getBlob().setName(pdfName+'.pdf');
//var attach = {fileName:'Monthly Report.pdf',content:pdf, mimeType:'application/pdf'};
var name = report.getRange("H1:H1").getValues(); // Get Name
var emailTo = report.getRange("H2:H2").getValues(); // Get email
var period = report.getRange("H3:H3").getValues(); // Get Reporting Period
var subject = " - TEST Monthly Report - " + period; // Construct the Subject Line
var message = "Hi " + name + ", here is your latest report for " + period; // email body text
// Send the freshly constructed email
MailApp.sendEmail(emailTo, subject, message, {attachments:[theBlob]});
}

Formatting PDF attachment in Google Apps Script (MailApp.sendEmail)

I set up a script to convert an office contact list in Google Sheets to PDF and email it to a list every month as an attachment. I'm trying to figure out how to format the PDF to be in landscape and remove gridlines and haven't had success. I'm relatively new to scripting so I'm sure I'm missing something. Here is my code. I'd appreciate any advice. Thanks!
function EmailSpreadsheetAsPDF() {
var file = DriveApp.getFileById('xxxxx_spreadsheet_key_xxxxx');
var formattedDate = Utilities.formatDate(new Date(), "GMT-7", "MMMM yyyy");
Logger.log(formattedDate);
var email = "xxxxx#xxxxx.xxx";
var subject = "Contact List - " + formattedDate;
var body = "Attached is the current contact list for " + formattedDate + "." + "\n\nPlease email xxxxx#xxxxx.xxx with any corrections or updates.";
MailApp.sendEmail(email, subject, body, {
name: 'xxxxx',
attachments: [file.getAs(MimeType.PDF)]
});
}
Yes, it is possible. You will however have to user UrlFetchApp for this purpose. As shown here(read post#89), you can export the file as a PDF while setting gridline visibility to false by using the following command:
var pdfBlob = UrlFetchApp.fetch("https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="
+docKey
+"&exportFormat=pdf&gid="
+printSheetIndex
+"&gridlines=false&printtitle=false&size=A4&sheetnames=false&fzr=true&portrait="
+portraitInd
+"&fitw=true"
, requestData).getBlob().setName(docName);
Read the provided link for more detailed information.

Get web methods dynamically for an asmx service

We have number of asmx services. I want to give an user a page with a textbox to input service url like http://abc.win.com/myservice/customerdata.asmx. When user hit "Load" button, dynamically I add all the web methods to the dropdown. I need some pointers:
1. How to dynamically get all the methods?
2. How can I get the SOAP request for the method selected? So that, we can replace the parameter values with actual values?
Appreciate your help.
Kuul13 : You need to modify your webservice URL like http://abc.win.com/myservice/customerdata.asmx?wsdl when user clicks on load button. then you can use we "ServiceDescription" class to get wsdl description and then iterate that to get method names in 'WebMethodInfoCollection' class.
To get SOAP request you need to use SOAPExtension class.This will give you SOAP Request and Response XML.Refere this link for that : http://blog.encoresystems.net/articles/how-to-capture-soap-envelopes-when-consuming-a-web-service.aspx?www.microsoft.com
For dynamically calling webservice look a this V.Good article
http://www.codeproject.com/KB/webservices/webservice_.aspx
Please reply me for any comment.
System.Net.WebClient client = new System.Net.WebClient();
System.IO.Stream stream = client.OpenRead("http://www.webservicex.net/globalweather.asmx?wsdl");
ServiceDescription description = ServiceDescription.Read(stream);
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12";
importer.AddServiceDescription(description, null, null);
importer.Style = ServiceDescriptionImportStyle.Client;
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
CodeNamespace nmspace = new CodeNamespace();
CodeCompileUnit unit1 = new CodeCompileUnit();
unit1.Namespaces.Add(nmspace);
ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
if (warning == 0)
{
CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
object[] args = new object[1];
args[0] = "India";
object wsvcClass = results.CompiledAssembly.CreateInstance("GlobalWeather");
MethodInfo mi = wsvcClass.GetType().GetMethod("GetCitiesByCountry");
RegExpForCountryCity(mi.Invoke(wsvcClass, args).ToString());
}
else
{
Console.WriteLine("Warning: " + warning);
}
void RegExpForCountryCity(string strHTML)
{
Regex qariRegex = new Regex(#"<Table>\s*<Country>(?<Country>[\s\S]*?)</Country>\s*<City>(?<City>[\s\S]*?)</City>\s*</Table>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
MatchCollection mc = qariRegex.Matches(strHTML);
string strCountryCity = "";
for (int i = 0; i < mc.Count; i++)
{
if (string.IsNullOrEmpty(strCountryCity))
strCountryCity = "Country: " + "<b>" + mc[i].Groups["Country"].Value + "</b>" + " " + "City: " + "<b>" + mc[i].Groups["City"].Value + "</b>" + "</br>";
else
strCountryCity += "</br>" + "Country: " + "<b>" + mc[i].Groups["Country"].Value + "</b>" + " " + "City: " + "<b>" + mc[i].Groups["City"].Value + "</b>" + "</br>";
}
Response.Write(strCountryCity);
}