【问题标题】:VBA send email using Gmail: transport failed to connectVBA 使用 Gmail 发送电子邮件:传输连接失败
【发布时间】:2017-11-28 18:26:30
【问题描述】:

运行下面的 Excel VBA 代码出现以下错误:

运行时错误-2147220973
传输无法连接到服务器

Public Function send_email()

Set cdomsg = CreateObject("CDO.message")
With cdomsg.Configuration.Fields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'NTLM method
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 465
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 10
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "mymail@gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "mypass"
.Update
End With
' build email parts
With cdomsg
.To = "mymail@gmail.com"
.From = "mymail@gmail.com"
.Subject = "the email subject"
.TextBody = "the full message body goes here. you may want to create a variable to hold the text"
.Send
End With
    Set cdomsg = Nothing
End Function

【问题讨论】:

  • 尝试使用端口 587 而不是 465
  • 它没有用

标签: vba excel gmail cdo.message


【解决方案1】:

现在我正在使用下面的代码,它工作正常。 不要忘记更改您的 gmail 配置以允许从其他应用发送电子邮件。

Sub sendEmail(gmail, password, targetEmail, subject, bodyContent)

    Dim Mail As New Message
    Dim Config As Configuration: Set Config = Mail.Configuration

    Config(cdoSendUsingMethod) = cdoSendUsingPort
    Config(cdoSMTPServer) = "smtp.gmail.com"
    Config(cdoSMTPServerPort) = 465
    Config(cdoSMTPAuthenticate) = cdoBasic
    Config(cdoSMTPUseSSL) = True
    Config(cdoSendUserName) = gmail
    Config(cdoSendPassword) = password
    Config.Fields.Update

    Mail.To = targetEmail
    Mail.from = Config(cdoSendUserName)
    Mail.subject = subject
    Mail.HTMLBody = bodyContent

    Mail.Send

End Sub

【讨论】:

    【解决方案2】:

    问题来源

    错字造成了这个混乱 - smptserverport 应该是 smtpserverport

    我尝试过的事情

    在解决这个问题的过程中,我尝试了很多东西。但现在我不太确定是否真的需要所有这些。 不过,有人可能会从列表中获得一些东西:

    几点提示:

    • 明文发送密码时应使用端口465
    • 发送安全密码时应使用端口587

    如果您需要在 VBA/VBS 中使用安全密码,您可以在 PowerShell 中使用这个小技巧 (source):

    Dim myPassword, cmd, shell, executor, securePassword
    myPassword = "ABCABCABC....."
    cmd = "powershell.exe ConvertTo-SecureString "& myPassword
    Set shell = CreateObject("WScript.Shell")
    Set executor = shell.Exec(cmd)
    executor.StdIn.Close
    securePassword = executor.StdOut.ReadAll
    

    【讨论】:

      猜你喜欢
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多