使用Powershell使用gmail发送电子邮件

kam*_*att 0 powershell gmail smtp

我试图通过使用Powershell脚本的gmail smtp服务器发送电子邮件。但我无法发送电子邮件..我正在使用以下脚本-

$EmailFrom = "bttpm@gmail.com"

$EmailTo = "kamlesh.bhatt@domain.com" 

$Subject = "Notification from XYZ" 

$Body = "this is a notification from XYZ Notifications.." 

$SMTPServer = "smtp.gmail.com" 

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 

$SMTPClient.EnableSsl = $true 

$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("bttpm", "Password"); 

$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Run Code Online (Sandbox Code Playgroud)

Ger*_*hes 5

这为我工作:

$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "username@gmail.com"
$Password = ""

$to = "user1@domain.com"
$cc = "user2@domain.com"
$subject = "Email Subject"
$body = "Insert body text here"
$attachment = "C:\test.txt"

$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
$message.cc.add($cc)
$message.from = $username
$message.attachments.add($attachment)

$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent"
Run Code Online (Sandbox Code Playgroud)

但是,您可能会收到以下错误消息:

"The SMTP server requires a secure connection or the client was not authenticated. 
The server response was: 5.5.1 Authentication Required. "
Run Code Online (Sandbox Code Playgroud)

这是因为Gmail的默认安全设置会阻止连接,如Google的自动消息所建议的那样。因此,只需按照消息中的说明进行操作,然后启用“访问较不安全的应用程序”即可。风险自负。:)

此处提供更多信息:http : //petermorrissey.blogspot.ro/2013/01/sending-smtp-emails-with-powershell.html