Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GmailMessage to PDF

Google Apps Script - Gmail

Would a GmailMessage (GmailThread) .getAsPdf() method be implemented? The expected output would be the same as print to PDF available in Gmail. This function is available on the website, so why not in Script?

This is necessary to quickly distribute select Gmail conversations to others/externals as PDF.

Also, GmailMessage.getAttachments() though in the online documents, does not exist in reality. Will this be implemented?

Thanks

like image 561
Riyaz Mansoor Avatar asked Dec 11 '25 20:12

Riyaz Mansoor


1 Answers

I tried this and worked well (not sure it's the only approach):

function getattach(){
var firstThread = GmailApp.getInboxThreads(0,1)[0];
var message = firstThread.getMessages()[0];
var attach = message.getAttachments();
Logger.log(attach[0].getDataAsString() )
if(attach.length>0){
var file=DocsList.createFile(attach[0])
var pdf=file.getAs('application/pdf').getBytes();
// for test purpose I send the pdf as attachment
var attach_to_send = {fileName: 'pdftest.pdf',content:pdf, mimeType:'application/pdf'};
   MailApp.sendEmail('[email protected]', 'Your test as PDF ', 'see attachment', {attachments:[attach_to_send]});
file.setTrashed(true);// delete after use ;-)
}
}

EDIT 1:removed

EDIT 2: here is a new version with the body in pdf attachment, html is supported as well (using DocsList services) , temporary docs are deleted. In one word : quite satisfying ;-)

function getAttachAndBody(){
  var firstThread = GmailApp.getInboxThreads(0,1)[0];
  var message = firstThread.getMessages()[0];
  var attach = message.getAttachments();
  var body = message.getBody();//is a string
  var bodydochtml = DocsList.createFile('body.html', body, "text/html")
  var bodyId=bodydochtml.getId()
  var bodydocpdf = bodydochtml.getAs('application/pdf').getBytes();
  if(attach.length>0){
    var file=DocsList.createFile(attach[0])
    var pdf=file.getAs('application/pdf').getBytes();
    var attach_to_send = {fileName: 'pdftest.pdf',content:pdf, mimeType:'application/pdf'};
    var body_to_send = {fileName: 'body.pdf',content:bodydocpdf, mimeType:'application/pdf'};
    MailApp.sendEmail('[email protected]', 'transfer email as pdf : body & attachment', 'see attachment', {attachments:[attach_to_send,body_to_send]});
    file.setTrashed(true);
    DocsList.getFileById(bodyId).setTrashed(true)
    }
}
like image 159
Serge insas Avatar answered Dec 14 '25 20:12

Serge insas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!