Home > Software design >  Import Password -credential
Import Password -credential

Time:12-28

I am trying to send a file to email. I found this code and it worked but I want to add the password automatically is there any solution ??


$MyEmail = "[email protected]"
$Password = "TEST2132"
$SMTP= "smtp.gmail.com"
$To = "[email protected]"
$Subject = "LOG FILE!"
$Creds = (Get-Credential -Credential "$MyEmail") 
$attachment = "C:\TEST.txt" 
Start-Sleep 2

Send-MailMessage -To $to -From $MyEmail -Subject $Subject -Attachment $attachment -SmtpServer $SMTP -Credential $Creds -UseSsl -Port 587 -DeliveryNotificationOption never

Prompt

CodePudding user response:

Non-secure method

Here is how you create a credential object from a password string.

# Some email credentials
$username = 'Username'
$password = 'Password' | ConvertTo-SecureString -AsPlainText -Force
$Creds = [PSCredential]::New($username,$password)

As it was pointed in the comments, setting a password directly in the script is insecure since anybody that could get access to the script would see the password.

Secret management module method

This method requires a little bit of preparation but is the best in my opinion since the password is retrieved from a secret vault instead of being readily available in your script.

Prerequisites

Modules

Install the following modules

Install-Module Microsoft.PowerShell.SecretManagement
Install-Module SecretManagement.JustinGrote.CredMan

Vault

Create a vault to store the email credentials and possibly many others in the future.

Register-SecretVault -ModuleName SecretManagement.JustinGrote.CredMan -Name 'Default'

Save the credentials into the vault.

$username = 'Username'
$password = 'Password' | ConvertTo-SecureString -AsPlainText -Force
$Creds = [PSCredential]::New($username, $password)
Set-Secret -Name 'SomeEmailCreds' -Secret $Creds -Vault Default

How to use

Once every prerequisites is filled, you can get the credentials from the local vault by using the Get-Secret statement. The Set-Secret should be nowhere in your script and you should use it only if you need to update your credentials at some point.

$Creds = Get-Secret -Vault Default -Name 'SomeEmailCreds'

Notes

Note that the vault is "per user" and "per machine" so it should be created on the user and the machine it will run from.

SecretManagement also have other modules than the CredsMan one by Justin Grote which use all sort of different vault so there are implementation for Azure key vaults, 1password, etc

  • Related