使用Powershell通过smtp发送邮件

摘要:# 配置SMTP服务器$smtpServer = 'smtp.example.com' # 例如:smtp.gmail.com$smtpPort = 587 # 对于TLS,使用587端口;对于SSL,使用465端口$smtpUser = 'your_emai

使用Powershell通过smtp发送邮件,源码如下,具体内容可以自行更改

# 配置SMTP服务器$smtpServer = 'smtp.example.com' # 例如:smtp.gmail.com$smtpPort = 587 # 对于TLS,使用587端口;对于SSL,使用465端口$smtpUser = 'your_email@example.com' # 你的邮箱地址$smtpPassword = 'your_password' # 你的邮箱密码(建议使用应用专用密码)# 创建邮件内容$fromAddress = 'your_email@example.com' # 发件人地址$toAddress = 'recipient@example.com' # 收件人地址$subject = 'Test Email' # 邮件主题$body = 'This is a test email sent from PowerShell.' # 邮件正文内容# 创建邮件对象$mailmessage = New-Object system.net.mail.mailmessage$mailmessage.from = $fromAddress$mailmessage.To.add($toAddress)$mailmessage.Subject = $subject$mailmessage.Body = $body# 配置SMTP客户端$smtp = New-Object system.net.mail.smtpclient$smtp.Host = $smtpServer$smtp.Port = $smtpPort$smtp.Credentials = New-Object System.Net.NetworkCredential($smtpUser, $smtpPassword)$smtp.EnableSsl = $true # 启用SSL/TLS加密# 发送邮件try {$smtp.Send($mailmessage)Write-Host 'Email sent successfully!'} catch {Write-Host "Error: $($_.Exception.Message)"}

来源:科学新学生

相关推荐