使用凭据从powershell命令行发送电子邮件

时间:2013-07-10 04:41:48

标签: windows email powershell

我正在尝试使用Windows 8和powersell从我的gmail ccoiunt发送一封电子邮件。这是我使用的代码:

Send-MailMessage -smtpServer 'smtp.gmail.com' -port 587 -from 'myself@gmail.com' -to 'myself@gmail.com' -subject 'Test' -body 'Body' –UseSsl

但我不知道如何添加凭据。如何在此单一代码行中添加用户名和密码? (无需加密密码)。

由于

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

     $EmailTo = "udit043.ur@gmail.com"  // abc@domain.com
     $EmailFrom = "udit821@gmail.com"  //xyz@gmail.com
     $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("udit821@gmail.com", "xxxxxxxx");    // xxxxxx-password
     $SMTPClient.Send($SMTPMessage)