【问题标题】:Send Powershell Email using Google 2FA?使用 Google 2FA 发送 Powershell 电子邮件?
【发布时间】:2018-03-12 23:58:24
【问题描述】:

我是一名 Powershell 开发人员,很好奇社区对电子邮件提供商发送每日通知的建议。

这是供个人使用的,但我知道 Google 的 2FA 阻止了这种事情的自动化。

基本上只是希望能够通过电子邮件(Send-MailMessage)向自己发送每日警报,任何输入都将不胜感激。

【问题讨论】:

    标签: .net powershell email automation


    【解决方案1】:

    Gmail 用户可以通过官方网站或使用第一方或第三方应用和服务来访问他们的帐户。第一方应用程序是例如 Google 的 Android 官方 Gmail 应用程序,而 Thunderbird 和 Windows 8 的邮件客户端应用程序是第三方应用程序。

    Google announced 早在 2014 年 4 月就表示,它将提高其服务的登录安全性,并影响任何向公司发送用户名和密码的应用程序。

    该公司当时建议切换到 OAuth 2.0,但直到现在才强制执行。

    如果您在 Google 的安全设置下打开新的 less secure 应用页面,您会注意到 Google 默认已禁用访问。

    注意:只有当您没有使用 Google Apps 或为帐户启用了双重身份验证时,您才会看到该页面。

    您可以在此处拨动开关以再次启用安全性较低的应用程序,从而重新获得访问权限。

    这里是使用混合代码批处理和 Powershell 脚本发送带有 SSL 身份验证的电子邮件的示例。

    只需将其保存为 Gmail_PS_Batch_Sender.bat

    <# : Batch portion
    @rem # The previous line does nothing in Batch, but begins a multiline comment block
    @rem # in PowerShell.  This allows a single script to be executed by both interpreters.
    @echo off & Mode 100,5 & color 0A
    Title Sending E-mail with SSL Authentification with an Hybrid code Batch and Powershell Script by Hackoo
    echo(
    rem # This a Powershell command executes the hybrid portion at the bottom of this script
    for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0}|out-string)"') do set "%%I"
    exit /b
    rem # End multi-line PowerShell comment block.  Begin PowerShell scripting.
    : end Batch / begin PowerShell hybrid code #>
    #################################### First 1 Step ###########################################
    # First Step we encrypt the Plain Text Password to an encrypted one using the key AES.key
    # Première étape, nous cryptons le mot de passe en clair vers un mot de passe chiffré
    # à l'aide de la clé AES.key
    $AppData = [Environment]::GetFolderPath('ApplicationData')
    $KeyFile = $AppData+"\AES.key"
    $Key = New-Object Byte[] 32   # You can use 16, 24, or 32 for AES 
    [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
    $Key | out-file $KeyFile
    $AppData = [Environment]::GetFolderPath('ApplicationData')
    $PasswordFile = $AppData+"\Password.txt"
    $Key = Get-Content $KeyFile
    $GmailUserName = Read-Host "Please enter your Gmail Account without ""@gmail.com"" "
    $Password = Read-Host "Please enter your Gmail Password to be encrypted " -AsSecureString `
    | ConvertFrom-SecureString -key $Key | Out-File $PasswordFile
    #################################### First 1 Step ###########################################
    
    #################################### Second 2 Step ##########################################
    # We send the email with our encrypted Credentials
    # Nous envoyons le courrier électronique avec les informations d'identification cryptés
    #############################################################################################
    Function Show-BalloonTip {
      [CmdletBinding(SupportsShouldProcess = $true)]
      param (
        [Parameter(Mandatory=$true)]$Text,
        [Parameter(Mandatory=$true)]$Title,   
        [ValidateSet('None', 'Info', 'Warning', 'Error')]$Icon = 'Info',
        $Timeout = 10000
      )
      Add-Type -AssemblyName System.Windows.Forms
    
      if ($script:balloon -eq $null) { $script:balloon = New-Object System.Windows.Forms.NotifyIcon }
    
      $path                    = Get-Process -id $pid | Select-Object -ExpandProperty Path
      $balloon.Icon            = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
      $balloon.BalloonTipIcon  = $Icon
      $balloon.BalloonTipText  = $Text
      $balloon.BalloonTipTitle = $Title
      $balloon.Visible         = $true
      $balloon.ShowBalloonTip($Timeout)
      Start-Sleep -s 10
      $balloon.Dispose()
    }
    ################################################################################################
    function Show-Message {
    
    param (
        [string]$Message = "Veuillez entrer votre message",
        [string]$Titre = "Titre de la fenêtre",
        [switch]$OKCancel,
        [switch]$AbortRetryIgnore,
        [switch]$YesNoCancel,
        [switch]$YesNo,
        [switch]$RetryCancel,
        [switch]$IconErreur,
        [switch]$IconQuestion,
        [switch]$IconAvertissement,
        [switch]$IconInformation
        )
    
    # Affecter la valeur selon le type de boutons choisis
    if ($OKCancel) { $Btn = 1 }
    elseif ($AbortRetryIgnore) { $Btn = 2 }
    elseif ($YesNoCancel) { $Btn = 3 }
    elseif ($YesNo) { $Btn = 4 }
    elseif ($RetryCancel) { $Btn = 5 }
    else { $Btn = 0 }
    
    # Affecter la valeur pour l'icone 
    if ($IconErreur) {$Icon = 16 }
    elseif ($IconQuestion) {$Icon = 32 }
    elseif ($IconAvertissement) {$Icon = 48 }
    elseif ($IconInformation) {$Icon = 64 }
    else {$Icon = 0 }
    
    # Charger la biblithèque d'objets graphiques Windows.Forms
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
    
    # Afficher la boite de dialogue et renvoyer la valeur de retour (bouton appuyé)
    $Reponse = [System.Windows.Forms.MessageBox]::Show($Message, $Titre , $Btn, $Icon)
    Return $Reponse
    }
    ################################################################################################
    $SuccessMsg = "The email was sent successfully ; Please, check your email !"
    $FailureMsg = "ERROR occurred while sending the email"
    $AppData = [Environment]::GetFolderPath('ApplicationData')
    $PasswordFile = $AppData+"\Password.txt"
    $keyFile = $AppData+"\AES.Key"
    $key = Get-Content $KeyFile
    $GmailEncryptedPassword = Get-Content $PasswordFile | ConvertTo-SecureString -Key $key
    $Credentials = New-Object -TypeName System.Management.Automation.PSCredential `
    -ArgumentList($GmailUserName,$GmailEncryptedPassword)
    $EmailFrom = $GmailUserName+"@gmail.com"
    $EmailTo = $EmailFrom
    $Subject = "Sending E-mail with SSL Authentification with an Hybrid code Batch and Powershell Script"
    $Body = (Get-Date -format F)  + "  Hello ! the sending email is working now with PowerShell and Batch Script!"
    $SMTPServer = "smtp.gmail.com"
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,587)
    $SMTPClient.EnableSsl = $true
    $SMTPClient.Credentials = $Credentials
    try
    {
      $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
      Show-Message -Message $SuccessMsg -Titre $SuccessMsg -IconInformation
      Show-BalloonTip -Text $SuccessMsg -Title $SuccessMsg -Icon 'Info'
    }
    catch
    {
      Show-Message -Message $_.Exception.Message -Titre $FailureMsg -IconErreur
      Show-BalloonTip -Text $_.Exception.Message -Title 'ERROR occurred while sending the email' -Icon 'Error' 
    }
    exit(1)
    

    【讨论】:

      【解决方案2】:

      如果您创建应用密码,您可以使用启用了两因素身份验证的 gmail。请参阅my answer hereGoogles documentation here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-24
        • 2015-05-15
        • 2016-07-21
        • 2010-09-25
        • 1970-01-01
        • 2021-04-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多