I'm trying to update users of my domain to a new adress ,basically the same command than gam which is : " gam update user userx username mailadress#x.com "
My goal is to make the same thing but using google apps script, the documentation isn't very helpful because "AdminDirectory.Users.update(resource, userKey)" is even not present in it.
function updateUserName() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var mailAdress= sheet.getRange(1, 1).getValue();
var user = AdminDirectory.Users.get(colAdresseMail);
user.emails = [address='newtest#mydomainname.com', primary=true];
Logger.log(user);
}
When I'm looking at logs, the address is now the new adress I want, but when I'm sending a mail to this adress, I have 2 mails , one with the mail I needed to have, and another mail delivery subsystem..
Maybe I forgot something?
In the web UI, the alias is added automatically when you change an email address. Based on my previous work with this and the results you're seeing, I believe GAM does it programmatically (GETs original address and inserts it as an alias during the change) if you're seeing that behavior. You could check this in the source for GAM here if you'd like to be 100% sure.
You will need to use something like the following insert to set the alias like you've updated the email address in your comment:
AdminDirectory.Users.Aliases.insert(alias, email)
The documentation on this can be found here within the Directory API section of the Google Developers site.
Related
I have created a number of tools that use Installable Triggers to send emails. Because I'm the one who wrote the scripts, and created the triggers, those emails are all sent from my account.
I am wondering if there is a way to create those installable triggers, not as my own account, but as a Google Group account. Ideally, I would like for those triggered emails to be sent from the Group's account, as opposed to my own. I am an Owner of the Google Group that I would like to use, so if it's possible, I should have the appropriate security. I'm just not sure if there's a way to log in as the Group, so that I can create the triggers from the Group's account, and therefore have the emails sent from the Group's account. Is that possible?
You don't need to sign in your group in the script, you just need to add the group email to your gmail settings Send mail as:
After adding it, a window will prompt you and add your group credentials there. After confirmation, you should be able to use that email as your parameter for sendEmail. See code below.
Code:
function sendEmailUsingGroupEmail() {
var alias = GmailApp.getAliases();
var groupEmail = "group#domain.com";
var toEmail = "test#domain.com";
var strSubject = "subject";
var strContent = "this is content";
// Check first if that email exists after adding
if(alias.includes(groupEmail))
GmailApp.sendEmail(toEmail,strSubject,strContent,{from: groupEmail});
}
I have the following code
var mailOptions = {};
mailOptions.attachments = attachmentArray;
mailOptions.htmlBody = htmlbody;
var alias = ??? // I have no idea what to put here. I've tried just putting in a string with the address
mailOptions.from = alias;
if(email){
GmailApp.sendEmail(email, subject,"",mailOptions);
I'm trying to send an email using an alias but I have multiple aliases to choose from. I saw somewhere that I can maybe use this
Gmail.Users.Settings.SendAs.Get
I should mention that while I wrote the script, I am not the owner of the spreadsheet. The original owner has a G Suite account, and wants to use their alias above. So it is not my alias, but they will be the one running the script.
First you should add an alias to Gmail. You can do this from the Gmail web app (see Send emails from a different address or alias) Also you might do this by using the Gmail API (see Managing Aliases
Once your Gmail account has one or more alias, you can use send email from an alias by adding its email address to the corresponing property of the GmailApp.sendEmail options argument.
Related
Email via Google Apps Script from another email address
It it possible to change the from address when using sendEmail?
I have a Google Sheet, its have several internal code (gs) and finish doing a list with mails and text, actually Im using a function to send mails:
function SendMail () {
var vAuxiliar = SpreadsheetApp.getActive().getSheetByName("Auxiliar");
var vLast = vAuxiliar.getDataRange().getNumRows();
var vDataRange = vAuxiliar.getRange("A2:E"+vLast);
var vValues = vDataRange.getValues();
for(var i in vValues) {
var vemailAddress = vValues[i][1];
var vMensaje = vValues[i][4];
var vSubject = 'Contact.';
MailApp.sendEmail(vemailAddress, vSubject, vMensaje);
};
};
Its works great but mails are incoming with my personal account, I need change this function to send mails with my enterprise account, we use MS Outlook, it is possible?
Thanks in advance!!!
You sure cannot use the Gmail service to send messages through your MS Outlook account.
But a possible workaround would be to create aliases for your MS Outlook account in your Gmail account, and then using this alias when sending.
GmailApp.sendEmail(to, 'Subject', 'A message sent from an alias!', {'from': "enterprise#example.com"});
But for using this from parameter in sendEmail you need to be able to retrieve it as an alias with getAliases().
Refer to this page to add your enterprise mail as an aliases to be able to use later.
Note that using the term alias here refers to the Gmail terminology as external email address. Do not check "Treat as alias" when configuring your MS Outlook account. This is another story.
Also as Ruben said in the comments you could try to ask if there are any API you can use to send mail. In that case you should try to use the URL fetch method.
I have a gradebook web app script which looks at a logged in student's email address, finds the email in the gradebook, and then displays the student's grades based on the column the email is in. The only problem is this only works if the spreadhseet is made public. How can I keep the spreadhseet private and still make this script work? I know that if I choose "Anyone with the link" it is unlikely someone will find the spreadsheet, but I'd prefer it to stay private. In addition, from the "Deploy as Web App" interface, the app must be executed as the user, not myself. Any ideas?
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheet/ccc?key=ID');
var sh1 = ss.getSheetByName('StudentGrades');
var logsheet = ss.getSheetByName('logsheet');
var data = sh1.getDataRange().getValues();
var user = Session.getEffectiveUser()
Logger.log(user)
function doGet() {
var app = UiApp.createApplication();
if(!getcol(user)){
var warn = app.createTextBox().setWidth('500').setValue("Your results are not available or you don't have permission to view these data");// if user is not in the list, warning + return
app.add(warn)
return app
}
var grid = app.createGrid(data.length, 2).setWidth('300px').setBorderWidth(1).setCellPadding(0).setCellSpacing(0).setStyleAttribute('borderCollapse','collapse').setId('grid');
var text = app.createLabel(user).setWidth('300px');
var col = getcol(user)
grid.setWidget(0,1,text).setText(0, 0, 'Results for');
grid.setStyleAttribute('textAlign','center')
for(n=1;n<data.length;++n){
grid.setText(n, 0, string(data[n][0]));
grid.setText(n, 1, string(data[n][col]));
grid.setStyleAttributes(n-1, 0, {'fontWeight':'bold','background':'#fff','border':'1px solid #000'});//left column css attributes
grid.setStyleAttributes(n-1, 1, {'fontWeight':'bold','background':'#fff','border':'1px solid #000'});//right column css attributes
}
app.add(grid);
return app
}
function string(value){
Logger.log(typeof(value))
if (typeof(value)=='string'){return value};// if string then don't do anything
if (typeof(value)=='number'){return Utilities.formatString('%.1f / 20',value)};// if number ther format with 1 decimal
if (typeof(value)=='object'){return Utilities.formatDate(value, Session.getTimeZone(), "MM-dd")};//object >> date in this case, format month/day
return 'error'
}
function getcol(mail){
if(data[0].toString().indexOf(mail.toString())!=-1){
for(zz=1;zz<data[0].length;++zz){
if(data[0][zz] == mail){var colindex=zz;break}
}
return colindex
}
return false
}
As I was suggesting in another of your posts you could setup a 'manual login' that will allow you to keep the spreadsheet private while running the webapp as yourself.
That implies that you'll have to create a list of user/password keys/values and that each student will have to enter his user name and password (you'll have to send them that information by email along with the link to the webapp) in a front end login screen before they gain access to the results display part.
I guess the best place to hold that list would be in script properties in the form of key:value.
If you need more that this to implement that solution (and if you think you'll go that way) feel free to ask.
EDIT following your comment :
Ok, I understand it can be unpleasant :)
Just wondering, wouldn't it be easier to store these data in the script itself in a scriptDB that you could automatically update with the spreadsheet values ?
The update would have to be executed by you (or by a timer trigger you create so that it runs on your account) and so the spreadsheet would remain private.
The students could then access the webapp with their accounts without accessing the spreadsheet.
From that service accessed as the user, call through urlget another apps script service published as yourself. That one does the ss-related work.
Might get timeouts on the service call though.
Why not setup a google group for each of your classes? Then add the google group to the SHARE permissions for the appropriate spreadsheet(s). This would have the added benefit of allowing you to easily send emails to your various classes via the appropriate google group. Under this scenario, your grade spreadsheets remain private and are only accessible by you and those email addresses listed in your google group.
I am a domain admin running the Google Apps for Education suite with many similar applications in place. You don't mention if you have administration rights for the domain or not, but I assume you do?
I keep all spreadsheets private and run the web apps as myself (giving the script the necessary access) which I think is precisely what you are aiming for?
I think your main issue stems from using .getEffectiveUser() which isn't providing you with what you need. I use Session.getActiveUser.getEmail() and then iterate through student objects (this is essentially just a sheet of student details returned as objects using the standard getRowsData function) to match the email value (if not found user = unknown).
This works perfectly for me with a student base of over 2000, all the data is private and the apps respond quickly serving personalised information.
If you'd like to see an example app please let me know, it's a little large to post here.
I've developed a web app with google script and code this in my gs.
var email = Session.getActiveUser().getEmail();
Logger.log(email);
// then do something to render the Email address on the page
After publishing the script, I log in with another account and execute the script.
Then the page display this:
This application was created by another user, not by Google.
This application has access to the following personal information: email address.
But still nothing in Log and the page display nothing.
I just don't get it...
Although it's not stated explicitly in the reference documentation for Session.GetActiveUser(), my testing confirmed that your web app needs to execute as the user accessing the web app to have access to getActiveUser(). I used the code below and the logging library described here.
Depending on the use case of your application, perhaps you could create a library containing a centralized ScriptDB instance to capture the active user email. Then, create another project that works with your private spreadsheet and the same scriptDB library.
var LOG_FILENAME = 'your-log-doc'
var LOG_PATH = 'folder/subfolder/third-folder'
function doGet() {
//Change variable above to a good path and filename for you
var x = LogLibrary.InitializeLogging(LOG_PATH, LOG_FILENAME)
Logger.log(x)
var email = Session.getActiveUser().getEmail();
Logger.log("Start email logging")
Logger.log(email);
LogLibrary.fnSaveLog() //Write the save and flush the logger content
// then do something to render the Email address on the page
var HTMLToOutput = '<html><h1>A header</h1><p>' + email + '</p></html>';
return HtmlService.createHtmlOutput(HTMLToOutput);
}
I've made some tests because I am looking for a solution about the same problem,and I conclude that :
so that function can works, the web app should be executed as "user accessing the web app", and for that, the web app should be configured so that can be executed as user accessing the web app
Note that : the user will be asked to authorise the script to access, edit and
manage it's drive also receiving and sending mails (which is not evident !! for all most of users of corse").
In the end that it depend of what you will use it for.
And in google documentation nothing is mentioned about this issue!!
For a simple function that returns the email address as a text to use as script or in google html forms.. etc :
function onOpen(){
var emailName = Session.getActiveUser().getEmail();
var optionsHtml = emailName.toString().split(",");
return optionsHtml;
}
Look in the gas issues forum (google). It hax been addressed many times. Basically you need to set it as run as user accessing the app if u expect users from outside your domain. Changing that setting will qlikely break your app depending on the permissions it needs
If your app is from before the 25th of June 2013, and you are using getEffectiveUser() or getUser() methods you will need to re-authorize the script because of the new authorization experience.
You can see the documentation here.
https://developers.google.com/apps-script/scripts_google_accounts#understandingPermissions
And do not forget to execute the script before deploying.
If you want to access the user's email, make sure you have added the "https://www.googleapis.com/auth/userinfo.email" email access policy in the appsscript .json
You can see the documentation here.
https://developers.google.com/apps-script/reference/base/session#authorization