Very strange, it doesn´t send an email

64 views
Skip to first unread message

ENEKO RODRIGUEZ

unread,
Jan 17, 2022, 5:50:51 AM1/17/22
to Google Apps Script Community
Egunon, Good morning!

First you will say why I put very strange... because until recently it worked, and without changing anything it has stopped working... and practically the same code in another excel sheet, if it works.

I try to make that when the user changes the value of a column to "SEND", send an email collecting the data from the excel... I have been checking each step (showing values ​​in the excel sheet, I don't know how to debug otherwise) and it seems which is fine up to the point of sending the email, and in case the email is sent I have tried with two forms that I have seen, using the gmailApp class and the Mail.App class... I can't think of any more... a little help? Does anyone see something that I've missed?

oh!!!! and it doesn't send the email and it no longer executes the following to the emai instruction, and the error it gives me has nothing to do with the email... by itself, it gives me the error but if the instruction supposedly works for me of the error (TypeError: Cannot read property 'getRow' of undefined at OnEdit (Code: 17:29)

I put all the code in a word document to keep the colors.
Thanks a lot
Noenviaemail.docx

Braja Patnaik

unread,
Jan 27, 2022, 4:00:30 PM1/27/22
to Google Apps Script Community
I guess this code would still work. You are probably trying to run the "onEdit(e)" function from the editor. Hence, you are getting  TypeError: Cannot read property 'getRow' of undefined at OnEdit as no event object is being passed to it. If you execute it by editing your data in the sheet, this error will not come.

ENEKO RODRIGUEZ

unread,
Jan 28, 2022, 6:14:15 AM1/28/22
to Google Apps Script Community
Good morning!!

Tahnks, but I'm executing it by editing my data in the sheet. I've done some changes in the code in the part of the error:

var hoja = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
   
var celdaModificada= hoja.getCurrentCell(); // hoja.getRange
var NumFila=celdaModificada.getRow();
Logger.log(JSON.stringify(NumFila))

var columna=celdaModificada.getColumn();
Logger.log(JSON.stringify(columna))

BUT, now the erro appear when it has to send the email (when the columna take the 10 value)
Captura.JPG

Sandi Berg

unread,
Jan 28, 2022, 8:24:33 AM1/28/22
to google-apps-sc...@googlegroups.com
You have to add the permissions for sending email to the manifest.

******ADVERTENCIA LEGAL Y PROTECCIÓN DE DATOS ******

Responsable: INSTITUTO DE LA BIENAVENTURADA VIRGEN MARÍA - CIF: R2800294G - Dirección postal: Los Mesejo, 10-12, bajo A, 28007 Madrid. Correo electrónico: in...@colegiosirlandesas.org. Delegado de Protección de Datos: d...@adhocasesoreslegales.com. El INSTITUTO DE LA BIENAVENTURADA VIRGEN MARÍA, en adelante IBVM, le informa de que los datos que nos proporcione serán utilizados con el fin de gestionar las comunicaciones que pudiera mantener con el personal de esta congregación. No se cederán sus datos salvo que exista una obligación legal. Los datos proporcionados se conservarán mientras no se solicite su supresión o durante el tiempo necesario para cumplir con las obligaciones legales. Usted tiene derecho a obtener confirmación sobre si en el IBVM estamos tratando sus datos personales, por tanto, tiene derecho a acceder a ellos, rectificar los datos inexactos o solicitar su supresión cuando ya no sean necesarios para los fines que fueron recogidos. A tal fin será suficiente el envío de una comunicación escrita indicando tal circunstancia y acreditando fehacientemente su identidad a las direcciones arriba mencionadas. También le informamos su derecho a presentar una reclamación ante la Agencia Española de Protección de Datos si considera que en el tratamiento de sus datos no se están respetando sus derechos.

La información contenida en el presente mensaje de correo electrónico es confidencial y su acceso únicamente está autorizado al destinatario original del mismo, quedando prohibida cualquier comunicación, divulgación, o reenvío, tanto del mensaje como de su contenido. En el supuesto de que usted no sea el destinatario autorizado, le rogamos borre el contenido del mensaje y nos comunique dicha circunstancia a través de un mensaje de correo electrónico a la dirección in...@colegiosirlandesas.org

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/b313384b-b016-4741-9cde-c3328da8dab5n%40googlegroups.com.

Braja Patnaik

unread,
Jan 28, 2022, 12:16:48 PM1/28/22
to Google Apps Script Community
Check this discussion:
https://stackoverflow.com/questions/29041866/mailapp-sendemail-error-message-do-not-have-permission-to-call-sendemail
Basically,  the onEdit(e) is a simple trigger and it has some restricted permissions that it cannot send email. The above discussion states how you can do a workaround.

ENEKO RODRIGUEZ

unread,
Jan 31, 2022, 5:00:36 AM1/31/22
to Google Apps Script Community
Thanks!!! Done.

I've changed teh name of the OnEdit procedure!!! Here all the code running!!!

/**
 * @OnlyCurrentDoc
 */

function onEditEneko(e){
 // Trigger, cuando un valoor cambia
  //e es el rango modificado

//quiero:
//   1- enviar un email
//   2- poner fecha de envio
//   3- si se cambia estado, cambiar color de la fila
//   4- si ya se ha enviado un email... avisar si se envia otra vez
var hoja = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
   
var celdaModificada= hoja.getCurrentCell(); // hoja.getRange
var NumFila=celdaModificada.getRow();
Logger.log(JSON.stringify(NumFila))

var columna=celdaModificada.getColumn();
Logger.log(JSON.stringify(columna))

//hoja.getRange(40,4).setValue(columna) , no entiendo, dice que error en getcolumn, pero con este codigo se ve que lo coge bien
  //depuracion
  //    hoja.getRange(43,11).setValue("Getcolumn")
  //    hoja.getRange(43,12).setValue(columna)

if (columna==10){  //Columna 1º0, columna J, se esta cambiando el enviar o no
  
    var dato= celdaModificada.getValue();
    
    if (dato == 'ENVIAR'){
    
      //pregyntamos si estamos seguros para enviar el mensaje
      ConfirmarSiEnviar(e,NumFila)
    }    
}
else if (columna==13){ //La columna del estado Columna 13, columna M  
  EstadoModificado(e)
}

} //Funcion OnEdit

function EnviarEmail(e,ParaQuien,NumFila) {
  
  //dependiendo de si es para Familias (0),  para Eneko (1) o para Txesmika(2)

  var hoja = SpreadsheetApp.getActiveSheet();  
  
  //Cuando enviamos el email, ponemos la fecha en la columna FechaEnvio
  
    //Recupero el numero de fila
    var celdaActiva=e.range;
    //var NumFila=celdaActiva.getRow()

    //Recupero el texto para el email, tambien, que cambia algo segun sea el destinatario        
    // Recupero el email de la persona
    var AvisoFinal=""

    //depuracion
    hoja.getRange(41,8).setValue(ParaQuien)

    if (ParaQuien==0) {
      dato= hoja.getRange(NumFila,2).getValue()
      BodyHtml="<body><h3>Egunon!!</h3>";
      AvisoFinal="eMail enviado a la familia"
    }
    else if (ParaQuien==1) {
        dato="erodr...@colegioirlandesas.com"
        BodyHtml="<body><h3>Egunon ENEKO!!</h3>";
        AvisoFinal="eMail enviado a Eneko"
    }
    else {
        dato="pa...@txesmika.com"
        BodyHtml="<body><h3>Egunon PAULA!!</h3>";
        AvisoFinal="eMail enviado a Paula-Txesmika"
    }
   
    var email=dato;
        
    //Recupero el asunto para el email
    //dato= "IncidenciaIrl " + hoja.getRange(NumFila,1).getValue() ;
    var FechaIncidencia=hoja.getRange(NumFila,1).getDisplayValue()
    dato= "IncidenciaIrl " +  FechaIncidencia
    var asunto=dato
     
    //Sigo con el cuerpo   
    BodyHtml=BodyHtml + "<table class='default'> <tr>"
    BodyHtml=BodyHtml + "<td><strong>    Fecha Incidencia </strong></td> <td>" + hoja.getRange(NumFila,1).getDisplayValue() + "</td></tr>";
    BodyHtml=BodyHtml+ "<tr><td><strong>    Título Incidencia </strong></td> <td>" + hoja.getRange(NumFila,3).getValue() + "</td></tr>";
    BodyHtml=BodyHtml+ "<tr><td><strong>    Alumno/Alumna</strong></td> <td>" + hoja.getRange(NumFila,6).getValue() + "</td></tr>";
    BodyHtml=BodyHtml+ "<tr><td><strong>    Incidencia</strong></td> <td>" + hoja.getRange(NumFila,8).getValue() + "</td></tr>";
     if (ParaQuien==1) {
       BodyHtml=BodyHtml + "<tr><td><strong>    Email Familia</strong></td> <td>" + hoja.getRange(NumFila,2).getDisplayValue() + "</td></tr>";
       BodyHtml=BodyHtml + "<tr><td><strong>    Observaciones Internas </strong></td> <td>" + hoja.getRange(NumFila,12).getValue() + "</td></tr>";
    }
    BodyHtml=BodyHtml + "<tr><td><strong>  Comentario Técnicos </strong></td> <td><i>" + hoja.getRange(NumFila,9).getValue() + "</i></td></tr> </table>";
    BodyHtml=BodyHtml + "<br><br> Un Saludo. </body>"

  ///////////////////////////////// HASTA AQUI PARECE QUE TODO BIEN //////////////////////////////
    GmailApp.sendEmail (email,asunto,'',{htmlBody: BodyHtml});
    //MailApp.sendEmail ({
    //  to: email,
    //  subject: asunto,
    //  htmlBody: BodyHtml 
    //})

    //Modifico la fecha de envio
    var FechaEnvio= new Date()
    var Year    = FechaEnvio.getFullYear();
    var Mes   = FechaEnvio.getMonth() + 1;
    var Day     = FechaEnvio.getUTCDate();
    var strFechaEnvio = Day + "-" + Mes + "-" + Year;

    /////////////////////////////////  aqui parece que fallña ///////////////////
    hoja.getRange(40,10).setValue(FechaEnvio)
    hoja.getRange(41,10).setValue(Year)
    hoja.getRange(42,10).setValue(Mes)
    hoja.getRange(43,10).setValue(Day)
    hoja.getRange(NumFila,11).setValue(strFechaEnvio)

    //Aviso de que se ha enviado el email.
    SpreadsheetApp.getUi().alert("Verificación",AvisoFinal,SpreadsheetApp.getUi().ButtonSet.OK)

    
  }

  function EstadoModificado(e){
    var hoja = SpreadsheetApp.getActiveSheet();
    var sheet=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

    var celdaModificada= e.range
      
    var dato= celdaModificada.getValue();
    
    //Recupero el numero de fila
    var celdaActiva=e.range;
    var NumFila=celdaActiva.getRow()

    //Calculamos la fecha de hoy
    var FechaHoy= new Date()
    var year    = FechaHoy.getFullYear();
    var month   = FechaHoy.getMonth() + 1;
    var day     = FechaHoy.getUTCDate();
    var  strFechaHoy= day + "-" + month + "-" + year ;
    
    if (dato=="Finalizado"){
      //Cambiamos el color a la fila
      //hoja.getrange(NumFila,1,1,15).setBackgroundRGB(15,177,56) //desde la columna 1, 15 columnas
      var RangioFila=sheet.getRange(NumFila,1,1,15);
      RangioFila.setBackgroundRGB(15,177,56);

      //Cambiamos la fechGFin
      hoja.getRange(NumFila,15).setValue(strFechaHoy)

      //Oculto la fila.
      sheet.hideRows(NumFila);

    }
    else if ((dato=='Espera Txesmika') || (dato=='Espera Familias'))  {
      //Cambiamos el color a la fila
      //hoja.getrange(NumFila,1,1,15).setBackgroundRGB(15,177,56) //desde la columna 1, 15 columnas
      var RangioFila=sheet.getRange(NumFila,1,1,15);

      //Cambiamos la fecha de espera
      hoja.getRange(NumFila,14).setValue(strFechaHoy)

      //segun que valor tenga dato ponemos un colo u otro y enviamos eMail
      if (dato=='Espera Txesmika'){
        RangioFila.setBackgroundRGB(74,134,232);
        EnviarEmail(e,2,NumFila)
      }
      else{
        RangioFila.setBackgroundRGB(142,124,195);
        ConfirmarSiEnviar(e,NumFila)
      }
         

    }
    else if (dato=='Eneko'){
      //Cambiamos el color a la fila
      //hoja.getrange(NumFila,1,1,15).setBackgroundRGB(15,177,56) //desde la columna 1, 15 columnas
      var RangioFila=sheet.getRange(NumFila,1,1,15);
    
      RangioFila.setBackgroundRGB(255,0,126);
           
      //Cambiamos la fecha de espera
      hoja.getRange(NumFila,14).setValue(strFechaHoy)

      EnviarEmail(e,1,NumFila)
    }
    
  }  //Funcion EstadoModificado

  function ConfirmarSiEnviar(e,NumFila) {
      var hoja = SpreadsheetApp.getActiveSheet();
      
      //pregyntamos si estamos seguros para enviar el mensaje
      var ui=SpreadsheetApp.getUi();
      var respuesta=ui.alert("Confirmacion","Estas seguro de enviar el mensaje a la familia?",ui.ButtonSet.YES_NO) //si ponemos prompt en lugar de alert, el  usuario puede introducir texto
      if (respuesta ==ui.Button.YES){
        
        EnviarEmail(e,0,NumFila)
        var celdaActiva=e.range;
        //var NumFila=celdaActiva.getRow()

        //Cambiamos el valor de estado Email a enviado
        hoja.getRange(NumFila,10).setValue("Enviado")
        } 

  }

  function AlumnadoNoPuede(e){
    var hoja=SpreadsheetApp.getActive();
         
    var dato= emailIntroducido.getRange(emailIntroducido.getRow, 16);

    if (dato=="#¡VALOR!"){
      hoja.getRange(30,2).setValue("NO ES UN ALUMNO")
    }

    //EnviarEmail(e,1)


  }

Reply all
Reply to author
Forward
0 new messages