RJython send Mail via .bat Firewall - r

We have .bat Files which call an R-script and generate some data and then send an email to certain users via rJython.
If I run this script in RStudio everything goes well and the mail is sent. But if i call the .bat file we get the following error.
It has probably something to do with the firewall in our company, can somebody help us out? We need to tell our IT departement something bc they cant help us either.
Error in jython.exec(rJython,mail): (-1, 'Unmapped exception:java.net.SocketException: Permission denied: connect') Execution halted
The R-Code to send the mail is:
#Sendmail Code
rJython<-rJython()
rJython$exec("import smtplib")
rJython$exec("from email.MIMEText import MIMEText")
rJython$exec("import email.utils")
rJython$exec("COMMASPACE = ', '")
recipients_string_j = paste("toaddrs = [",recipients_string,"]",sep="")
#mail config
mail<-c( fromaddr = 'test#XXX.com",
recipients_string_j,
paste("msg = MIMEText('",data.frame,"','html')",sep="",collapse=""),
paste("msg['Subject'] = 'DUMMY SUBJECT'"),
"msg['From'] = fromaddr",
"msg['To']= COMMASPACE.join(toaddrs)",
"server = smtplib.SMTP('00.00.00.000')",
"server.sendmail(fromaddr, toaddrs, msg.as_string())",
"server.quit()")
#send mail
jython.exec(rJython,mail)

Related

Passing files in POST using Requests in Python

I'm getting below error when making a requests call post method
{'detail': [{'loc': ['body', 'files'], 'msg': 'field required', 'type': 'value_error.missing'}]}
I tried
response = requests.post("url",headers={mytoken},params=p,files=files)
files = { "file 1": open("sample.pdf",'rb'), "file 2":open("sample11.pdf",'rb')}
I want to get 200 status but I'm getting 422 validation error. Any Idea Why? Its for API Testing purpose, Im new to this I've been debugging this for whole day but still couldn't figure out.
It is not clear from the question what kind of a request the server is expecting. Also, its not clear the exact code snippet you are using too.
From the question, the snippet looks like as follows,
response = requests.post("url",headers={mytoken},params=p,files=files)
files = { "file 1": open("sample.pdf",'rb'), "file 2":open("sample11.pdf",'rb')}
if so, that means you are reading files after you send the request, may be thats why the server complained about missing files field.
See the below example on how you can send two files to an endpoint expecting files.
import requests
import logging
logger = logging.getLogger(__name__)
post_url = "https://exampledomain.local/upload"
file1 = open("sample1.pdf", "rb")
file2 = open("sample2.pdf", "rb")
files = {"file1": file1, "file2": file2}
headers = {"Authorization": "Bearer <your_token_here>"}
params = {"file_type": "pdf"}
response = requests.post(post_url, files=files, headers=headers, params=params)
file1.close()
file2.close()
logger.debug(response.text)

Use Powershell to download attached excel file from Servicenow ticket

I'm currently working on a powershell script that should be able to download an attached excel file from a service now ticket, before I explain more please see the basic flow of the automation below.
The user will be asked to enter the ticket number.
The system will then find that incident ticket to accurately get the excel file needed(I saw online that I need to use sys_id).
It will then be downloaded to a specific path on the user's machine. ex: "C:\downloads\Demo\".
Following all this, I found a sample script online that I'm trying to configure to match my needs; however, I'm not sure where to get the values on that sample script. You can check the bullets below the script for the questions I have in mind.
$IncidentNumber = Read-Host -Prompt 'Enter Incident Request #'
#$admin = "admin"
#$password = "admin" | ConvertTo-SecureString -AsPlainText -Force
#$Credential = New-Object pscredential -ArgumentList ($admin,$password)
$Uri = "https://dev42835.service-now.com/api/now/table/incident?sysparm_query=number=$($IncidentNumber)&sysparm_fields=sys_id&sysparm_limit=1"
$IncidentResult = Invoke-RestMethod -Uri $Uri #-Method Get -Credential $Credential
if($IncidentResult.result.sys_id -ne $null) {
$IncidentAttachments = Invoke-RestMethod -Uri "https://dev42835.service-now.com/api/now/attachment?sysparm_query=table_sys_id=$($IncidentResult.result.sys_id)" #-Method Get -Credential $Credential
$IncidentAttachments.result | Select file_name , download_link
}
else{
"Incident Not Found!"
}
Do I really need the credentials to run the script? If yes, is there a way to
remove the need of the credentials?
Where can I get the URL that is assigned to the $URI variable?
I'm new to powershell automation so I would appreciate it if you can recommend better approach if there are any.
Yes, you need credentials but don't hard code them like that. Instead you can use built-in method Get-Credential that will securely collect your username and password. The user will have to enter their own ServiceNow credentials each time this is run.
My version only has one thing you need to configure, the $SubDomain variable which is specific to your tenant.
$SubDomain = "YourServiceNowSubdomaingoeshere" # Configure this per tenant
$Credential = Get-Credential
If(!$Credential){
# User Cancelled
exit 1
}
$IncidentNumber = Read-Host -Prompt 'Enter Incident Request #'
$Uri = "https://$SubDomain.service-now.com/api/now/table/incident?sysparm_query=number=$($IncidentNumber)&sysparm_fields=sys_id&sysparm_limit=1"
$IncidentResult = Invoke-RestMethod -Uri $Uri -Method Get -Credential $Credential
if($IncidentResult.result.sys_id -ne $null) {
$IncidentAttachments = Invoke-RestMethod -Uri "https://$SubDomain.service-now.com/api/now/attachment?sysparm_query=table_sys_id=$($IncidentResult.result.sys_id)" -Method Get -Credential $Credential
$IncidentAttachments.result | Select file_name , download_link
}
else{
"Incident Not Found!"
}
Yes you need credentials.
Your URI is the URL of your servicenow instance. Change the dev42835 portion to match. If you're unsure of your instance, contact servicenow support.
https://dev42835.service-now.com
If you use the REST API explorer, you can view API endpoints and versions which will help with forming your requests. You do need to have the rest_api_explorer role to access the REST API Explorer. If you do not have this role, contact your service-now admin requesting it.
https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/integrate/inbound_rest/task/t_GetStartedAccessExplorer.html

Error: could not find function "workspace"

I am trying to access an Azure ML Workspace from RStudio using the script:
install.packages("AzureML")
ws <- workspace(
id = "xxxxxxxxxxxxxxxxxxxxxxxxxx",
auth = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
)
and get the error could not find function "workspace"
The workspace id and primary authorisation token are 100% correct.
I am very new to R and presume I am making a schoolboy error.
Any help gratefully appreciated ?
Cheers,
Andy
https://cran.r-project.org/web/packages/AzureML/vignettes/getting_started.html suggests the following:
library(AzureML)
ws <- workspace(
id = "your workspace ID",
auth = "your authorization token"
)
Your code is missing the library(AzureML) part.
Documentation of library: https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/library
After calling that, the workspace function should be available.

Send SQLite db file from within app

I have looked everywhere and I can't find out how to do this; I'm so frustrated...
How can I allow the user to send (via email) the SQLite db file?
That's it in a nutshell. I can convert it to string and attach, but I want to send the actual db file. And I'm using a new phone that doesn't have an external SD card.
The app is just a form that the user fills out, then it's saved to a SQLite database. That works wonderfully. As does printing the db to string (text) and then sending it. But, I want the user to email the actual db file (so I can use C# to read, process it, and "recreate" a real form).
Or should I be using something other than SQLite?
Edit: This is as far as I've made it. It seems to work, but it does not actually attach the file or rather the file is "blank/empty". Debug log says no such file or directory. screenshot of debug log here:http://imgur.com/oyzdtuJ
//trying again to send a SQL db file
//this seems to work and shows that it's attaching a file, but the file is empty so it won't attach
//gmail will say "cant attach empty file"
private void sendFile(String email){
File myFile = this.getFileStreamPath("testresults.db");
if(myFile != null) {
Log.d("LOG PRINT SHARE DB", "File Found, Here is file location: " + myFile.toString());
}else {
Log.w("Tag", "file not found!");
}
Uri contentUri = FileProvider.getUriForFile(this, "com.columbiawestengineering.columbiawest.MainActivity", myFile);
Log.d("LOG PRINT SHARE DB", "contentUri got: here is contentUri: " + contentUri.toString());
//grant permision for app with package "com.columbiawestengineering.columbiawest", eg. before starting other app via intent
this.grantUriPermission("com.columbiawestengineering.columbiawest", contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
Log.d("LOG PRINT SHARE DB", "permission granted, here is contentUri: " + contentUri.toString());
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("application/octet-stream");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "blaaa subject");
String to[] = { email };
shareIntent.putExtra(Intent.EXTRA_EMAIL, to);
shareIntent.putExtra(Intent.EXTRA_TEXT, "blah blah message");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivityForResult(Intent.createChooser(shareIntent, "Send mail..."), 1252);
//revoke permisions
this.revokeUriPermission(contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
See this answer
Android Utility to send sqlite db to server
You could do this any number of ways. I'd say posting it to a web service is easiest. If you can only use email then I'd compress and encode it and attach it to an email but that sounds painful.
Solved. FileProvider cannot access the database directory. The db file must be copied to the files directory before it is attached. See solution here:Android: FileProvider "Failed to find configured root"

Sending an attachment from Shiny

I have created an application using Shiny and uploaded to the server that belongs to shinyapps.io; I have tested it and all is fine. My application creates via the server.R a text file that I would like to send to my email when a user finishes performing a task. I want to send that file to my email because I do not see a way in which to see the files that my shiny application outputs in the shinyapps.io admin tool. So bottomline, how can I send a file from a shiny application to my email?
For example if I have the following:
library(sendmailR)
datos<-read.table("data.txt")
to <- "<loretta#gmail.com>"
subject <- "Email Subject"
body <- "Email body."
mailControl=list(smtpServer="ASPMX.L.GOOGLE.COM")
sendmail(from="localhost",to=to,subject=subject,msg=body,control=mailControl)
attachmentObject <- mime_part(name=datos)
bodyWithAttachment <- list(body,attachmentObject)
sendmail(from="localhost",to=to,subject=subject,msg=bodyWithAttachment,control=mailControl)
I would like to know what I should put in the from part, I mean I have put it localhost, but I need to put the address of where the shiny application is running; from where I can get that?
Also when I run the above code, not in a Shiny environment, but as a script I got the following error after the sendmail part:
Error in wait_for(code) :
SMTP Error: 5.5.2 Syntax error. g22si4860678yhc.87 - gsmtp
any help would be great
This works for me for sending email from outlook using the mailR library:
library(mailR)
bodyMsg <- "Some message to be included in the body of the email"
send.mail(from = "sender#xyz.com", to = "receiver#xyz.com", subject = "Some topic",
body = bodyMsg , authenticate = TRUE, html = TRUE, send = TRUE, attach.files = file.path(folder, fileName),
smtp = list(host.name = "abcdef.xyz.com", port = 587, user.name = "sender#xyz.com", passwd = "password", tls = TRUE))}

Resources