Ton
Ton

Reputation: 9806

Send email from powershell command line with credentials

I am trying to send an email from my gmail ccoiunt in just one single line using windows 8 and powersell. This is the code I use:

Send-MailMessage -smtpServer 'smtp.gmail.com' -port 587 -from '[email protected]' -to '[email protected]' -subject 'Test' -body 'Body' –UseSsl

But I don't know how to add the credentials. How can I add username and password to this single code line? (there is no need to encrypt the password).

Thanks

Upvotes: 2

Views: 7407

Answers (2)

Tom
Tom

Reputation: 107

Send-MailMessage -smtpServer 'smtp.gmail.com' -port 587 -from '[email protected]' -to '[email protected]' -subject 'Test' -body 'Body' –UseSsl -Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "myUsername", (ConvertTo-SecureString -String "myPassword" -AsPlainText -Force))

Upvotes: 2

udit043
udit043

Reputation: 1620

     $EmailTo = "[email protected]"  // [email protected]
     $EmailFrom = "[email protected]"  //[email protected]
     $Subject = "zx"  //subject
     $Body = "Test Body"  //body of message
     $SMTPServer = "smtp.gmail.com" 
     $filenameAndPath = "G:\abc.jpg"  //attachment
     $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("[email protected]", "xxxxxxxx");    // xxxxxx-password
     $SMTPClient.Send($SMTPMessage)

Upvotes: 1

Related Questions