我正在尝试使用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)
答案 0 :(得分:4)
这对我有用:
$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"
但是,您可能会收到以下错误消息:
"The SMTP server requires a secure connection or the client was not authenticated.
The server response was: 5.5.1 Authentication Required. "
这是因为Gmail的默认安全设置会阻止来自Google的自动消息所建议的连接。因此,只需按照消息中的说明操作,启用“访问安全性较低的应用程序”。风险自负。 :)
此处有更多信息:http://petermorrissey.blogspot.ro/2013/01/sending-smtp-emails-with-powershell.html
答案 1 :(得分:1)
使用powershell发送带附件的电子邮件 -
$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)
答案 2 :(得分:1)
" SMTP服务器需要安全连接或客户端未经过身份验证。服务器响应为:5.5.1需要身份验证。"
我最近遇到了这个问题,尝试通过我的Gmail帐户自动发送邮件。我不喜欢允许"访问不太安全的应用程序"。我想要前瞻性安全。所以我继续搜索。
我的解决方案是启用" 2-Step"验证。这提供了一种更安全的解决方案,因为它为您的脚本提供了一个备用密码来访问您的帐户。
Stefan的链接也有这个解决方案,但是它已经隐藏在评论中了,直到我通过搜索我的Gmail帐户找到它之后我才发现它。这就是我在这里发帖的原因。