Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email credentials when using send-mailmessage command

I have searched through many many forums and they do explain how to do this but the technical language is just too difficult to understand as I'm very new to powershell. I would like this explained to me step by step (baby steps). I would like to run this powershell command in a batch file (.bat). I have a batch file that does robocopy backups weekly and I want the batch file to send me a email when the backup is complete. The only issue I have is the credentials, I get a pop-up box asking for the user name and password. When I eneter this information the email will send successfully. Here is what I have;

Using: powershell V2.0 Windows 7 Ultimate

Powershell -command send-mailmessage -to [email protected] -from [email protected] -smtp smtp.broadband.provider.com -usessl -subject 'backup complete' 
like image 376
user3089120 Avatar asked Feb 14 '23 08:02

user3089120


2 Answers

$from = "[email protected]" 
$to = "[email protected]" 
$smtp = "smtpAddress.com" 
$sub = "hi" 
$body = "test mail"
$secpasswd = ConvertTo-SecureString "yourpassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential($from, $secpasswd)
Send-MailMessage -To $to -From $from -Subject $sub -Body $body -Credential $mycreds -SmtpServer $smtp -DeliveryNotificationOption Never -BodyAsHtml
like image 62
Niranjan Malviya Avatar answered Feb 20 '23 14:02

Niranjan Malviya


You could pass the credential object in your same command - which would avoid the popup:

Powershell -Command 'Send-MailMessage -to "[email protected]" -from "[email protected]" -smtp "smtp.broadband.provider.com" -usessl -subject "backup complete" -credential (new-object System.Net.NetworkCredential("user","pass","domain"))'

I'd recommend storing the username/password in a somewhat more safer format, but this should do your trick.

like image 33
Harald F. Avatar answered Feb 20 '23 13:02

Harald F.