运行下面的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
答案 0 :(得分:0)
一个错字导致了此混乱- smptserverport 应该是 smtpserverport !
在解决此问题的方法上,我尝试了很多事情。但是现在我不确定是否真的需要所有这些东西。 仍然有人可能会从列表中获得一些好处:
如果需要在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
答案 1 :(得分:-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