Send-mailmessage with attachment - task

I have a ps1 script which runs conditionally upon an event from Task Scheduler. The event that triggers my script is another task that finishes and writes "... completed successfully" to the Task Scheduler event log. When this occurs, my script sends and HTML email (send-mailmessage) with an attached file to specific users.
The problem is that it works when I run it manually but when I set up the condition (still sends the email) but doesn't attach the file!... here's my code:
$HTML = #"
<!DOCTYPE html>
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8">
<TITLE></TITLE>
$Messages
</body></html>
"#
$SMTPServer = "smtp.myserver.com"
$SMTPPort = "1234"
$Username = "xyz#mycompany.com"
$Password = "xyz-password"
$to = "Automation#xxxxx.net"
$bcc = "testuser#xyz.net"
$subject = "My Import Alert"
$attachment = "(unc path to the .csv)-$(get-date -f yyMMdd).csv"
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $HTML
$message.IsBodyHTML = $true
$message.to.add($to)
$message.bcc.add($bcc)
$message.from = "Import Alerts <Automation#xyz.net>"
$message.attachments.add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$SMTPMessage=New-Object System.Net.Mail.MailMessage
$smtp.send($message)
So, when it's manually run, it works fine (with attachement)... every time!!
When I have it set to run via task scheduler it works (sends the email) BUT THRE'S NO ATTACHMENT! IT WAS RUNNING FINE, UNTIL TODAY(!)
I don't know how to debug or test this at all... any help would be greatly appreciated!!
Thank you!!!
B-

I'm relatively new myself and have only been working with PowerShell for about 7 months now, but I might be able to help. While I generally use the Send-MailMessage -To -From, etc. (have you tried this?) method to send emails, I have used the method you show on occasion as well.
From looking at your code and comparing it to what I have, I note that you're missing $attachment = New-Object System.Net.Mail.Attachment($emailAttach, $attachmentType). I also see that I've made a comment in my script that you need to include $message.Dispose() after you send the email or there will be a write lock on the attachment in question.
Hopefully this helps!

I had the same problem. The following two-liner works for me and can be scheduled. Change gmail-user#gmail etc. to match your account and credentials:
$credentials = new-object Management.Automation.PSCredential “gmail-user#gmail.com”, (“gmail-user's password” | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -From "gmail-user#gmail.com" -to "someone-else#gmail.com" -Subject "Some subject"
-Body "Some body" -SmtpServer "smtp.gmail.com" -port 587 -UseSsl
-Credential $credentials -Attachments "C:\an-attachment.txt"

Related

Twilio Not doing anything when receiving SMS

I'm creating a sample application that will post alerts to the website in the event of a hurricane or service outage. I'm not using Laravel.
I set the URL of the page in my account settings. The first time I sent a message I received a HTTP error that it had timed out without being given a reponse. I edited the XML and tried again.
I'm not getting anything in the database and I'm not getting the response. I also wrote a sample page that posts a value to see if it would work and it did. It posted it into the database and showed correctly formatted XML.
<?php
$response = 'This number cannot handle automated replies...';
$twiml1 = '<response><sms>';
$twiml2 = '</sms></response>';
require_once '../settings/db.php';
if (isset($_POST['body'])) {
$body = strip_tags($_POST['body']);
$sql = "INSERT INTO alerts (message) VALUES ('$body')";
$result = $db->query($sql);
if ($result) {
$response = 'Thanks. Your message was posted on the website.';
} else {
$response = 'There was a query error.';
}
}
header('Content-type: application/xml');
echo $twiml1;
echo $response;
echo $twiml2;
Twilio developer evangelist here.
Parameters that are sent via webhooks from Twilio are case sensitive and start with a capital letter. The text for an incoming message is sent as the Body parameter so checking for $_POST['body'] won't work.
I'd update your conditional to:
if (isset($_POST['Body'])) {
$body = strip_tags($_POST['Body']);
// The rest
}
Also, just to note, the <Sms> element has been deprecated. I'd use the <Message> element instead. The tags are case sensitive too, so I'd update the TwiML section to this:
$twiml1 = '<Response><Message>';
$twiml2 = '</Message></Response>';
Let me know if that helps at all.

update Jenkins credentials by script

I have a Jenkins server running on Windows. It stores a username:password in the credentials plugin. This is a service user that gets its password updated regularly.
I'm looking for a way to run a script, preferably Powershell, that will update that credential in the Jenkins password store so that it's always up to date when I use it in a build job script.
The password is managed by a Thycotic Secret Server install so I should be able to automate the process of keeping this password up to date, but I have found almost no leads for how to accomplish this, even though the blog post by the guy who wrote the credentials api mentions almost exactly this scenario and then proceeds to just link to the credentials plugin's download page that says nothing about how to actually use the api.
Update
The accepted answer works perfectly, but the rest method call example is using curl, which if you're using windows doesn't help much. Especially if you are trying to invoke the REST URL but your Jenkins server is using AD Integration. To achieve this you can use the following script.
Find the userId and API Token by going to People > User > configure > Show API Token.
$user = "UserID"
$pass = "APIToken"
$pair = "${user}:${pass}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = #{ Authorization = $basicAuthValue }
Invoke-WebRequest `
-uri "http://YourJenkinsServer:8080/scriptler/run/changeCredentialPassword.groovy?username=UrlEncodedTargetusername&password=URLEncodedNewPassword" `
-method Get `
-Headers $headers
Jenkins supports scripting with the Groovy language. You can get a scripting console by opening in a browser the URL /script of your Jenkins instance. (i.e: http://localhost:8080/script)
The advantage of the Groovy language (over powershell, or anything else) is that those Groovy scripts are executed within Jenkins and have access to everything (config, plugins, jobs, etc).
Then the following code would change the password for user 'BillHurt' to 's3crEt!':
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl
def changePassword = { username, new_password ->
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
Jenkins.instance
)
def c = creds.findResult { it.username == username ? it : null }
if ( c ) {
println "found credential ${c.id} for username ${c.username}"
def credentials_store = Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()
def result = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
c,
new UsernamePasswordCredentialsImpl(c.scope, c.id, c.description, c.username, new_password)
)
if (result) {
println "password changed for ${username}"
} else {
println "failed to change password for ${username}"
}
} else {
println "could not find credential for ${username}"
}
}
changePassword('BillHurt', 's3crEt!')
Classic automation (/scriptText)
To automate the execution of this script, you can save it to a file (let's say /tmp/changepassword.groovy) and run the following curl command:
curl -d "script=$(cat /tmp/changepassword.groovy)" http://localhost:8080/scriptText
which should respond with a HTTP 200 status and text:
found credential 801cf176-3455-4b6d-a461-457a288fd202 for username BillHurt
password changed for BillHurt
Automation with the Scriptler plugin
You can also install the Jenkins Scriptler plugin and proceed as follow:
Open the Scriptler tool in side menu
fill up the 3 first field taking care to set the Id field to changeCredentialPassword.groovy
check the Define script parameters checkbox
add 2 parameters: username and password
paste the following script:
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl
def changePassword = { username, new_password ->
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
jenkins.model.Jenkins.instance
)
def c = creds.findResult { it.username == username ? it : null }
if ( c ) {
println "found credential ${c.id} for username ${c.username}"
def credentials_store = jenkins.model.Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()
def result = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
c,
new UsernamePasswordCredentialsImpl(c.scope, null, c.description, c.username, new_password)
)
if (result) {
println "password changed for ${username}"
} else {
println "failed to change password for ${username}"
}
} else {
println "could not find credential for ${username}"
}
}
changePassword("$username", "$password")
and click the Submit button
Now you can call the following URL to change the password (replacing the username and password parameter): http://localhost:8080/scriptler/run/changeCredentialPassword.groovy?username=BillHurt&password=s3crEt%21 (notice the need to urlencode the parameters' value)
or with curl:
curl -G http://localhost:8080/scriptler/run/changeCredentialPassword.groovy --data-urlencode 'username=BillHurt' --data-urlencode "password=s3crEt!"
sources:
Printing a list of credentials and their IDs
Create UserPrivateKeySource Credential via Groovy?
credential plugin source code
Scriptler plugin
Search engine tip: use keywords 'Jenkins.instance.', 'com.cloudbees.plugins.credentials' and UsernamePasswordCredentialsImpl
Decided to write a new answer although it is basically some update to #Tomasleveil's answer:
removing deprecated calls (thanks to jenkins wiki, for other listing options see plugin consumer guide)
adding some comments
preserve credentials ID to avoid breaking existing jobs
lookup credentials by description because usernames are rarely so unique (reader can easily change this to ID lookup)
Here it goes:
credentialsDescription = "my credentials description"
newPassword = "hello"
// list credentials
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
// com.cloudbees.plugins.credentials.common.StandardUsernameCredentials to catch all types
com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials.class,
Jenkins.instance,
null,
null
);
// select based on description (based on ID might be even better)
cred = creds.find { it.description == credentialsDescription}
println "current values: ${cred.username}:${cred.password} / ${cred.id}"
// not sure what the other stores would be useful for, but you can list more stores by
// com.cloudbees.plugins.credentials.CredentialsProvider.all()
credentials_store = jenkins.model.Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()
// replace existing credentials with a new instance
updated = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
cred,
// make sure you create an instance from the correct type
new com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl(cred.scope, cred.id, cred.description, cred.username, newPassword)
)
if (updated) {
println "password changed for '${cred.description}'"
} else {
println "failed to change password for '${cred.description}'"
}
I never found a way to get the Groovy script to stop updating the credential ID, but I noticed that if I used the web interface to update credentials, the ID did not change.
With that in mind the script below will in effect script the Jenkins web interface to do the updates.
Just for clarification, the reason this is important is because if you are using something like the Credentials binding plugin to use credentials in your job, updating the ID to the credential will break that link and your job will fail. Please excuse the use of $args rather than param() as this is just an ugly hack that I will refine later.
Note the addition of the json payload to the form fields. I found out the hard way that this is required in this very specific format or the form submission will fail.
$username = $args[0]
$password = $args[1]
Add-Type -AssemblyName System.Web
#1. Log in and capture the session.
$homepageResponse = Invoke-WebRequest -uri http://Servername.domain.com/login?from=%2F -SessionVariable session
$loginForm = $homepageResponse.Forms['login']
$loginForm.Fields.j_username = $username
$loginForm.Fields.j_password = $password
$loginResponse = Invoke-WebRequest `
-Uri http://Servername.domain.com/j_acegi_security_check `
-Method Post `
-Body $loginForm.Fields `
-WebSession $session
#2. Get Credential ID
$uri = "http://Servername.domain.com/credential-store/domain/_/api/xml"
foreach($id in [string]((([xml](Invoke-WebRequest -uri $uri -method Get -Headers $headers -WebSession $session).content)).domainWrapper.Credentials | Get-Member -MemberType Property).Name -split ' '){
$id = $id -replace '_',''
$uri = "http://Servername.domain.com/credential-store/domain/_/credential/$id/api/xml"
$displayName = ([xml](Invoke-WebRequest -uri $uri -method Get -Headers $headers -WebSession $session).content).credentialsWrapper.displayName
if($displayName -match $username){
$credentialID = $id
}
}
#3. Get Update Form
$updatePage = Invoke-WebRequest -Uri "http://Servername.domain.com/credential-store/domain/_/credential/$credentialID/update" -WebSession $session
$updateForm = $updatePage.Forms['update']
$updateForm.Fields.'_.password' = $password
#4. Submit Update Form
$json = #{"stapler-class" = "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl";
"scope"="GLOBAL";"username"="domain\$username";"password"=$password;"description"="";"id"=$id} | ConvertTo-Json
$updateForm.Fields.Add("json",$json)
Invoke-WebRequest `
-Uri "http://Servername.domain.com/credential-store/domain/_/credential/$credentialID/updateSubmit" `
-Method Post `
-Body $updateForm.Fields `
-WebSession $session

Redeployment with Powershell in Multi Tenant Environment

I want to redeploy a multiple tenants using powershell. We have 100+ tenants in UIT and I don't want to do this manually. In order to redeploy, I have to use a specific link and log in. My question is, if it is possible to do this in an automated way using powershell. Here is what I have so far:
Function SendRequest($tenantName)
{
$url = "http://<machine-name>/$tenantName/Account /LogOn?ReturnUrl=%2f$tenantName%2fadmin%2fdeploytenant%3fsyncmetadata%3dtrue&syncmetadata=true"
$req = [system.Net.WebRequest]::Create($url)
$req.Credentials = [System.Net.NetworkCredential]::($username, (ConvertTo-SecureString $pwd -AsPlainText -force))
try
{
$res = $req.GetResponse()
}
catch [System.Net.WebException]
{
$res = $_.Exception.Response
}
$int = [int]$res.StatusCode
$status = $res.StatusCode
Write-Host $status
return "$int $status"
}
The status that is returned is "200 OK" but it does not redeploy. Maybe I need to log in first and then send another request with the redeployment parameters. So what would be the best way to accomplish this?
Maybe this is just a snippet of your code, but I'm seeing you reference $username and $pwd without actually feeding in a username and password.
Perhaps that could that explain the lack of a successful redeploy.

How To Get Twitter Followes_Count To echo with commas

I am working on pulling the number of twitter followers into my Wordpress page but running into a small problem I cannot figure out. I imagine it would be a quick fix...do you think you can help?
The issue is the output reads:
11131
I would like it to read:
11,131
You see the comma in the correct position...not sure how to get that to render in the right format. Here is the code I am working with:
<?php
$data = json_decode(file_get_contents('https://api.twitter.com/1/user/lookup.json?screen_name=erinschreyer'), true);
echo $data[0]['followers_count'];
?>
Any help is appreciated...
It would work with that:
<?php
$data = json_decode(file_get_contents('https://api.twitter.com/1/users/lookup.json?screen_name=erinschreyer'), true);
$followers = $data[0]['followers_count'];
echo number_format($followers);
?>
See number_format()

Stuck messages in ZeroMQ

I'm having a strange problem with ZeroMQ, in which some messages get stuck, and just get unstuck when new messages arrive. It's like the new messages push the stuck messages on the door (terrible comparison, i know).
My code is quite simple:
rep.php
$context = new ZMQContext;
$receiver = new ZMQSocket($context, ZMQ::SOCKET_PULL);
$receiver->connect("tcp://localhost:8022");
$receiver2 = new ZMQSocket($context, ZMQ::SOCKET_PULL);
$receiver2->connect("tcp://localhost:8024");
for (;;) {
echo $receiver->recv() . PHP_EOL;
echo $receiver2->recv() . PHP_EOL;
}
cnt.php and cnt2.php (same code, different ports)
$context = new ZMQContext;
$work = new ZMQSocket($context, ZMQ::SOCKET_PUSH);
$work->bind('tcp://*:8022');
$work->send('Hello World');
cnt.php sends to 8022 and cnt2.php to 8024. They get executed from time to time and send messages to rep.php. However, some messages get stuck. If i sent 4 messages from cnt.php, nothing is received, but when i send 1 from cnt2.php, i get 5 messages at once. Any ideas?
I am no PHP expert here but guessing the syntax and functionality. Please correct me if I am wrong
echo $receiver->recv() . ' - ' . $receiver2->recv();
recv() should be a blocking call.
$receiver->recv() blocks until some message is received.
But echo does not echo the message immediately
You are again blocked on $receiver2->recv()
Only when you send message from the other file does echo work because it is waiting on $receiver2->recv()
Since you want to process the socket recv() independently, you should use polling or event based asynchronous I/O.
[Attempted solution]
$poll = new ZMQPoll();
$poll->add($receiver, ZMQ::POLL_IN);
$poll->add($receiver2, ZMQ::POLL_IN);
$readable = $writeable = array();
while(true) {
$events = $poll->poll($readable, $writeable);
foreach($readable as $socket) {
$message = $socket->recv();
echo $message, PHP_EOL;
}
}
Adapted from : http://zguide.zeromq.org/php:rrbroker

Resources