here there is a simple script to send an email.
If I run it using Gmail settings (ie smtp.gmail.com on port 465 or 587) the script doesn't work returning the error
Server error response: 5.7.0 Authentication Required
# graphical stuff
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName PresentationFramework
# import modules
$workdir = Get-Location
Import-Module -Name "$workdir\Modules\Forms.psm1" # module for windows forms
$answ = [System.Windows.MessageBox]::Show("Configure for sending mail alerts?",'ALERTS','YesNo','Info')
if ($answ -eq "Yes") {
# dialog box
$formail = New-Object System.Windows.Forms.Form
$formail.Text = "CONFIG"
$formail.Size = "500,300"
$formail.StartPosition = 'CenterScreen'
$formail.Topmost = $true
$address = New-Object System.Windows.Forms.Label
$address.Location = New-Object System.Drawing.Size(10,20)
$address.Size = New-Object System.Drawing.Size(120,20)
$address.Text = "Mail address:"
$formail.Controls.Add($address)
$addressbox = New-Object System.Windows.Forms.TextBox
$addressbox.Location = New-Object System.Drawing.Point(130,20)
$addressbox.Size = New-Object System.Drawing.Size(300,20)
$formail.Add_Shown({$addressbox.Select()})
$formail.Controls.Add($addressbox)
$passwd = New-Object System.Windows.Forms.Label
$passwd.Location = New-Object System.Drawing.Size(10,50)
$passwd.Size = New-Object System.Drawing.Size(120,20)
$passwd.Text = "Password:"
$formail.Controls.Add($passwd)
$passwdbox = New-Object System.Windows.Forms.MaskedTextBox
$passwdbox.PasswordChar = '*'
$passwdbox.Location = New-Object System.Drawing.Point(130,50)
$passwdbox.Size = New-Object System.Drawing.Size(300,20)
$formail.Add_Shown({$passwdbox.Select()})
$formail.Controls.Add($passwdbox)
$smtp = New-Object System.Windows.Forms.Label
$smtp.Location = New-Object System.Drawing.Size(10,80)
$smtp.Size = New-Object System.Drawing.Size(120,20)
$smtp.Text = "SMTP server:"
$formail.Controls.Add($smtp)
$smtpbox = New-Object System.Windows.Forms.TextBox
$smtpbox.Location = New-Object System.Drawing.Point(130,80)
$smtpbox.Size = New-Object System.Drawing.Size(300,20)
$formail.Add_Shown({$smtpbox.Select()})
$formail.Controls.Add($smtpbox)
$port = New-Object System.Windows.Forms.Label
$port.Location = New-Object System.Drawing.Size(10,110)
$port.Size = New-Object System.Drawing.Size(120,20)
$port.Text = "Port:"
$formail.Controls.Add($port)
$portbox = New-Object System.Windows.Forms.TextBox
$portbox.Location = New-Object System.Drawing.Point(130,110)
$portbox.Size = New-Object System.Drawing.Size(300,20)
$portbox.Text = '587'
$formail.Add_Shown({$portbox.Select()})
$formail.Controls.Add($portbox)
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = "150,160"
$OKButton.Size = '100,30'
$OKButton.Text = "Ok"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$formail.AcceptButton = $OKButton
$formail.Controls.Add($OKButton)
$result = $formail.ShowDialog()
# setting credentials
$usr = $addressbox.Text
$pwd = ConvertTo-SecureString $passwdbox.Text -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($usr, $pwd)
# define email content
$subject = 'TestMail.ps1'
$body = "Questa mail è stata mandata da uno script PowerShell"
# sending email
$ErrorActionPreference= 'Stop'
Try {
Send-MailMessage -From $addressbox.Text `
-To $addressbox.Text `
-Subject $subject `
-Body $body `
-SmtpServer $smtpbox.Text `
-UseSsl `
-Port $portbox.Text `
-Credential $credential
$ErrorActionPreference= 'Inquire'
}
Catch {
Write-Output "`nError: $($error[0].ToString())"
$answ = [System.Windows.MessageBox]::Show("Sending alert email failed",'WARNING','Ok','Warning')
}
}
In the cmdlet Send-MailMessage I haven't found any parameter to force authentication. How can I effectively send an email?
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required:
Solutions in order of likely hood to help.
Check if the user has 2fa enabled if so you will need an apps password
Check your Captcha loc
Look into Xoauth2
I solved the issue. As stated here, I have to:
1 - Force the script to use TLS 1.2
2 - Turn off two-factor authentication and allow access to insecure apps
Thank you DaImTo for the inspiration
Related
I am trying to check against the credential manager for any "Domain" entry, If "Domain" entry DOESN"T exist then a pop up window will appear for user to enter username and password. If it exist then simply stop script.
This PowerShell script is suppose to run at windows login in order to add domain credentials if they don't exist in the Windows Credential Manager, and then maps a network drive. If the script detects no domain credentials added in the Windows Credential Manager - then it will prompt the user to enter it.
I am confused at where i am wrong in my logic, when the code runs it ignores the IF statement and carries on popping the window for username & password even if there is a domain user in the Windows Credential Manager and runs the cmdkey /add and net use command.
I am deploying this script using Intune, and i have tested it without the IF statement and it works fine. I am trying to make the IF statement work first before testing it again.
This is my code:
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$error.clear()
try {
cmdkey /list | foreach {
if($_ -match 'Domain')
{
[PSCustomObject]#{Account = $matches.1}
[System.Windows.Forms.MessageBox]::Show("Already exist!")
}
else {
# Captures username
#-------------------------------------------------------------------------
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = "Enter Username"
$form.Size = New-Object System.Drawing.Size(300,200)
$form.StartPosition = "CenterScreen"
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = "Enter Username: "
$form.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,40)
$textBox.Size = New-Object System.Drawing.Size(260,20)
$form.Controls.Add($textBox)
$form.Topmost = $True
$form.Add_Shown({$textBox.Select()})
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$x = $textBox.Text
$x
}
# Captures password
#-------------------------------------------------------------------------
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = "Enter Password"
$form.Size = New-Object System.Drawing.Size(300,200)
$form.StartPosition = "CenterScreen"
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = "Enter Password: "
$form.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,40)
$textBox.Size = New-Object System.Drawing.Size(260,20)
$form.Controls.Add($textBox)
$form.Topmost = $True
$form.Add_Shown({$textBox.Select()})
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$x2 = $textBox.Text
$x2
}
cmdkey.exe /add:ae7msd-dc /user:$x /pass:$x2
net use U: "\\SERVER\FOLDER" /persistent:yes
break
}
}
}
catch { [System.Windows.Forms.MessageBox]::Show("Not Working!") }
if (!$error) {
[System.Windows.Forms.MessageBox]::Show("IT'S DONE!")
}
This is the output i get on the Powershell editor when there is no DOMAIN user added to the Windows Credential Manager:
PS C:\Users\hadi> C:\temp\add-cred.ps1
GAC Version Location
--- ------- --------
True v4.0.30319 C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll
hmohsen
Abc!2345
CMDKEY: Credential added successfully.
The command completed successfully.
OK
This is what i get when running the script even though there is already a domain user added to the windows credential manager:
PS C:\Users\hadi> C:\temp\add-cred.ps1
GAC Version Location
--- ------- --------
True v4.0.30319 C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll
hmohsen
Abc!2345
CMDKEY: Credential added successfully.
net : System error 85 has occurred.
At C:\temp\add-cred.ps1:124 char:2
+ net use U: "\\SERVER\FOLDER" /persistent:yes
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (System error 85 has occurred.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
The local device name is already in use.
OK
My aim is to stop the script the script when there is an entry for a Domain user in the Windows Credential Manager, but the script keeps going anyway.
The logic is flawed, but how can i fix it please!
The problem with your code lies within this statement:
cmdkey /list | foreach {
if($_ -match 'Domain')
The if statement never evaluates to true because the match is never true.
The cmdkey /list command returns an array of formatted strings. The string you want to match would be Type: Domain (with whitespace potentially before and after).
Changing your code to the following should result in getting the correct matches:
cmdkey /list | ForEach-Object {
if($_ -like '*Type: Domain*')
{
[PSCustomObject]#{Account = $matches.1}
[System.Windows.Forms.MessageBox]::Show("Already exist!")
}
I can open my mailbox in exchange online with EWS and Powershell
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
$service.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $mail, $password
$service.URL = New-Object Uri("https://outlook.office365.com/EWS/Exchange.asmx")
$view = New-Object Microsoft.Exchange.WebServices.Data.ItemView($numOfEmailsToRead, $index)
$folderview = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10)
$folderview.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.Webservices.Data.BasePropertySet]::FirstClassProperties)
$folderview.PropertySet.Add([Microsoft.Exchange.Webservices.Data.FolderSchema]::DisplayName)
$folderview.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
$folderfindResults = $service.FindFolders([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $folderview)
$SearchFilterContainsSubString = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Paramerter)
$SearchFilterNot = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($SearchFilterContainsSubString)
foreach ($InboxFolder in $folderfindResults) {
$findResultsItems = $InboxFolder.findItems($SearchFilterNot,$view)}
How do I change the code to open a mailbox to which I have full access?
In your example you need to use the Mailbox overload for Folder id so change
$folderfindResults = $service.FindFolders([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $folderview)
$SearchFilterContainsSubString = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Paramerter)
$SearchFilterNot = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($SearchFilterContainsSubString)
foreach ($InboxFolder in $folderfindResults) {
$findResultsItems = $InboxFolder.findItems($SearchFilterNot,$view)}
To
$MailboxToAccess = "blah#blah.com"
$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxToAccess)
$folderfindResults = $service.FindFolders($folderid, $folderview)
$SearchFilterContainsSubString = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Paramerter)
$SearchFilterNot = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($SearchFilterContainsSubString)
foreach ($InboxFolder in $folderfindResults) {
$findResultsItems = $InboxFolder.findItems($SearchFilterNot,$view)}
Here is a simple example of connecting to a different mailbox
$MailboxName = New-Object Microsoft.Exchange.WebServices.Data.Mailbox("support#domain.com") #specifies which mailbox EWS should connect to
$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
For more detailed info please read this blog: https://gsexdev.blogspot.com/2016/10/ews-basics-accessing-and-using-shared.html
Thank you for your support.
I was able to do it with the line
$service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$Mailbox);
Resolve.
I was getting a 401 error. The error was because I had overwritten the credentials. Now everything works.
In Exchange the executing user needs the role
"ApplicationImpersonation"
I have a PowerShell command that will get an output of how many CAL's I have installed and how many are used. I would like to instead of write-host, change it to a variable so that I can add it to the body of an email and have it run on a schedule, to email me weekly reports on usage, I would like to have the variable something like $report as shown in the $body of the email, this is what I have so far..
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$summaryEntries|ForEach {Write-Host $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "Alert: CAL USAGE "
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I have used both parts of this script separately, but I would like to join them together, to make more useful. Thanks in advance PowerShell newbie..
Here is the full code that I used to get this to work, simply changing 'Write-Host' to 'Write-Output'
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$Report = $summaryEntries|ForEach {Write-Output $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "RDS CAL USAGE REPORT"
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I am trying to create a GUI that can create new AD Users.
My Problem: When I press the Button "Speichern" it does not use the Data in the textboxs to create the AD User. Instead this text comes in the command console:
New ADUser cmdlet at command pipeline location 1
Specify values for the following parameters:
Surname:
If I enter the Surname it will create the User with this Surname.
This is my Powershell script:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
Import-Module ActiveDirectory
#GUI Oberfläche
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(500,500)
$Form.Text = "Benutzer hinzufügen"
#-------Labels-----------
#Label Benutzer hinzufügen
$labeladduser = New-Object System.Windows.Forms.Label
$labeladduser.Location = New-Object System.Drawing.Size(200,10)
$labeladduser.Size = New-Object System.Drawing.Size(200,30)
$labeladduser.Text = "Benutzer hinzufügen"
$labeladduser.Name = "Benutzer hinzufügen"
$Form.Controls.Add($labeladduser)
#Label Vorname
$Labelvorname = New-Object System.Windows.Forms.Label
$Labelvorname.Location = New-Object System.Drawing.Size(10,50)
$Labelvorname.Size = New-Object System.Drawing.Size(100,20)
$Labelvorname.Text = "Vorname"
$Labelvorname.Name = "Vorname"
$Form.Controls.Add($Labelvorname)
#Label Nachname
$Labelnachname = New-Object System.Windows.Forms.Label
$Labelnachname.Location = New-Object System.Drawing.Size(10,80)
$Labelnachname.Size = New-Object System.Drawing.Size(100,20)
$Labelnachname.Text = "Nachname"
$Labelnachname.Name = "Nachname"
$Form.Controls.Add($Labelnachname)
#Label Vollständigername
$LabelVn = New-Object System.Windows.Forms.Label
$LabelVn.Location = New-Object System.Drawing.Size(10,110)
$LabelVn.Size = New-Object System.Drawing.Size(100,20)
$LabelVn.Text = "Vollständigername"
$LabelVn.Name = "Vollständigername"
$Form.Controls.Add($LabelVn)
#Label Benutzeranmeldename
$LabelBa = New-Object System.Windows.Forms.Label
$LabelBa.Location = New-Object System.Drawing.Size(10,140)
$LabelBa.Size = New-Object System.Drawing.Size(150,20)
$LabelBa.Text = "Benutzeranmeldename"
$LabelBa.Name = "Benutzeranmeldename"
$Form.Controls.Add($LabelBa)
#-------Buttons-------
#Close GUI Button
$BTcancel = New-Object System.Windows.Forms.Button
$BTcancel.Location = New-Object System.Drawing.Size(400,180)
$BTcancel.Size = New-Object System.Drawing.Size(75,23)
$BTcancel.Text = "Cancel"
$BTcancel.Name = "Cancel"
$BTcancel.Add_Click({$Form.Close()})
$Form.Controls.Add($BTcancel)
#Speichern Button
$BTsave = New-Object System.Windows.Forms.Button
$BTsave.Location = New-Object System.Drawing.Size(320,180)
$BTsave.Size = New-Object System.Drawing.Size(75,23)
$BTsave.Text = "Speichern"
$BTsave.Name = "Speichern"
$Form.Controls.Add($BTsave)
#------Textfields------
#Textfeld Vorname
$Textboxvorname = New-Object System.Windows.Forms.TextBox
$Textboxvorname.Location = New-Object System.Drawing.Size(200,50)
$Textboxvorname.Size = New-Object System.Drawing.Size(200,20)
$addv = $Textboxvorname.Text
$Form.Controls.Add($Textboxvorname)
#Textfeld Nachname
$Textboxnachname = New-Object System.Windows.Forms.TextBox
$Textboxnachname.Location = New-Object System.Drawing.Size(200,80)
$Textboxnachname.Size = New-Object System.Drawing.Size(200,20)
$addn = $Textboxnachname.Text
$Form.Controls.Add($Textboxnachname)
#Textfeld Vollständigername
$TextboxVa = New-Object System.Windows.Forms.TextBox
$TextboxVa.Location = New-Object System.Drawing.Size(200,110)
$TextboxVa.Size = New-Object System.Drawing.Size(200,20)
$addVa = $TextboxVa.Text
$Form.Controls.Add($TextboxVa)
#Textfeld Benutzeranmeldename
$TextboxBa= New-Object System.Windows.Forms.TextBox
$TextboxBa.Location = New-Object System.Drawing.Size(200,140)
$TextboxBa.Size = New-Object System.Drawing.Size(200,20)
$addBa = $TextboxBa.Text
$Form.Controls.Add($TextboxBa)
#------Funktionen--------
#Add User
$BTsave.Add_Click({
New-ADuser
-Name $addVa
-Path "Ou=Users, DC=domain, DC=com"
-Givenname = $addv
-Surname =$addn
-SamAccountName $addBa
-AccountPassword (ConvertT0-SecureString "<redacted>" -AsPlainText -Force)
})
[void] $Form.ShowDialog()
Does someone have a solution for my problem?
I believe the problem is when you are assigning values.
taking this as an example:
#Textfeld Benutzeranmeldename
$TextboxBa= New-Object System.Windows.Forms.TextBox
$TextboxBa.Location = New-Object System.Drawing.Size(200,140)
$TextboxBa.Size = New-Object System.Drawing.Size(200,20)
$addBa = $TextboxBa.Text
$Form.Controls.Add($TextboxBa)
when you're assigning a value to $addBa the value of $TextboxBa.Text is most likely empty!
So you should probably change your $BTsave.Add_Click event to directly access the textbox value(s) rather than the empty variable.
Also worth noting is that PowerShell doesn't take kindly to line breaks. If you want to avoid long lines you have to add a back-tick character.
#Add User
$BTsave.Add_Click({
New-ADuser `
-Name $TextboxVa.Text `
-Path "Ou=Users, DC=domain, DC=com" `
-Givenname $Textboxvorname.Text `
-Surname $Textboxnachname.Text `
-SamAccountName $TextboxBa.Text `
-AccountPassword (ConvertTo-SecureString "<redacted>" -AsPlainText -Force)
})
Below has a full form.
Create User and add to groups.
NewUserForm PowershellGUI
https://github.com/jcvnstdn/jcvnstdn/blob/main/UserCreationForm.PS1
I have written a PowerShell script that will create an email, however I can't seem to attach a file. The file does exist and PowerShell can open it, Could anyone tell me what I'm doing wrong?
$ol = New-Object -comObject Outlook.Application
$message = $ol.CreateItem(0)
$message.Recipients.Add("Deployment")
$message.Subject = "Website deployment"
$message.Body = "See attached file for the updates made to the website`r`n`r`nWarm Regards`r`nLuke"
# Attach a file this doesn't work
$file = "K:\Deploy-log.csv"
$attachment = new-object System.Net.Mail.Attachment $file
$message.Attachments.Add($attachment)
If you are on PowerShell 2.0, just use the built-in cmdlet Send-MailMessage:
C:\PS>Send-MailMessage -from "User01 <user01#example.com>" `
-to "User02 <user02#example.com>", `
"User03 <user03#example.com>" `
-subject "Sending the Attachment" `
-body "Forgot to send the attachment. Sending now." `
-Attachment "data.csv" -smtpServer smtp.fabrikam.com
If you copy/paste this watch out for the extra space added after the backtick. PowerShell doesn't like it.
I got the above to work by removing the line
$attachment = new-object System.Net.Mail.Attachment $file
and changing
$message.Attachments.Add($attachment)
to
$message.Attachments.Add($file)
While the solution provided by #Keith Hill would be better, even with a lot of goggling I couldn't get it to work.
This worked for me using powershell-
Define Variables:
$fromaddress = "donotreply#pd.com"
$toaddress = "test#pd.com"
$Subject = "Test message"
$body = "Please find attached - test"
$attachment = "C:\temp\test.csv"
$smtpserver = "mail.pd.com"
Use the variables in the script:
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)
You can use send-mailmessage or system.net.mail.MailMessage to accomplish it. Interestingly, there is a significant execution time difference between the two approaches. You can use measure-command to observe the execution time of the commands.
I have experienced such problem, (windows 10 / PS 5.1)
My SMTP is not authentified or secure ...
I have to finish by this line "MyAttacheObject.Dispose()"
... / and finally that's work :!
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$attach.Dispose()
this is my code with two attachments :
# Email configuration NO AUTH NO SECURE
$emailHost = "smtp.bot.com"
$emailUser = ""
$emailPass = ""
$emailFrom = "myemail#bot.com"
$emailsTo=#("toyoumylove#bot.com","toyoumybad#bot.com")
$emailSubject = $title
$emailbody=$body
$attachment1 = #($PATh+$outFile)
$attachment2 = #($PATh+$inFile)
#End of parameters
$msg = New-Object System.Net.Mail.MailMessage
$msg.from = ($emailFrom)
foreach ($d in $emailsTo) {
$msg.to.add($d)
}
$msg.Subject = $emailSubject
$msg.Body = $emailbody
$msg.isBodyhtml = $true
$att = new-object System.Net.Mail.Attachment($attachment1)
$msg.Attachments.add($att)
$att = new-object System.Net.Mail.Attachment($attachment2)
$msg.Attachments.add($att)
$smtp = New-Object System.Net.Mail.SmtpClient $emailHost
$smtp.Credentials = New-Object System.Net.NetworkCredential($emailUser, $emailPass);
$smtp.send($msg)
$att.Dispose()
"yourpassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "D:\Password.txt"
# The above command will encrypt the password you need to run this command only one time
# 1.Sign in to your work or school account, go to the My Account page, and select Security info.
2.Select Add method, choose App password from the list, and then select Add.
3.Enter a name for the app password, and then select Next. it will give password
# you should use this password in above mentioned command
$User = "mymail#company.net"
$File = "C:\Users\username\Desktop\Mail\Password.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString -AsPlainText -Force)
$EmailTo = "mymail#company.net"
$EmailFrom = "mymail#company.net"
$Subject = "SERVICE STOPPED"
$Body = "SERVICE STOPPED PFA Document to get more details."
$SMTPServer = "smtp.office365.com"
$filenameAndPath = "C:\Users\username\Desktop\new.txt"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password);
$SMTPClient.Send($SMTPMessage)
I needed to drop the "-AsPlainText -Force"
$emailCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $emailUser, (Get-Content $emailPasswordFile | ConvertTo-SecureString)