VBA Excel-从Excel发送邮件

我有下面的代码行命令button单击事件发送邮件。

Private Sub CommandButton1_Click() Dim cdoConfig Dim msgOne Set cdoConfig = CreateObject("CDO.Configuration") With cdoConfig.Fields .Item(cdoSendUsingMethod) = cdoSendUsingPort .Item(cdoSMTPServerPort) = 557 .Item(cdoSMTPServer) = "smtp.emailsr.com" 'SMTP server goes here '.Item(cdoSendUserName) = "My Username" '.Item(cdoSendPassword) = "myPassword" .Update End With Set msgOne = CreateObject("CDO.Message") Set msgOne.Configuration = cdoConfig msgOne.To = "adbc@adbc.com" msgOne.from = "bcda@adbc.com" msgOne.Subject = "Test CDO" msgOne.TextBody = "It works just fine." msgOne.Send End Sub 

当我执行这个我面临像运行时错误2147220977(8004020f)错误:自动化错误此订阅的事件类是在一个无效的分区

 msgOne.Send 

上面的行在执行期间给出错误。 所以我转移到发送电子邮件的CDO方法。现在我执行以下代码。

 Dim iMsg As Object Dim iConf As Object Dim strbody As String Dim Flds As Variant Set iMsg = CreateObject("CDO.Message") Set iConf = CreateObject("CDO.Configuration") iConf.Load -1 ' CDO Source Defaults Set Flds = iConf.Fields With Flds .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mysmtpserver.com" .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "mymailId" .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "Mypassword" .Update End With strbody = "Hi there" & vbNewLine & vbNewLine & _ "This is line 1" & vbNewLine & _ "This is line 2" & vbNewLine & _ "This is line 3" & vbNewLine & _ "This is line 4" With iMsg Set .Configuration = iConf .To = "tomailid" .CC = "" .BCC = "" .From = "mymailid" .Subject = "New" .TextBody = strbody .Send End With 

发送给我一个错误,如运行时错误-2147220977(8004020f):服务器拒绝一个或多个收件人地址。 服务器响应是:554 5.7.1:发件人地址被拒绝:访问被拒绝有时候就像是运行时错误 – '2147220975(80040211)自动化错误

您正在使用的代码将在VBScript或其他类似的语言中工作,如果您注册CDOtypes库。 types库包含属性cdoSendUsingMethod等,所以你不必使用完整的urn。 在VBA中,你必须使用完整的骨灰盒。 Ron De Bruin在http://www.rondebruin.nl/cdo.htm有很好的参考。

在他的网站上,您可以看到您的代码和VBA所需的区别,具体如下:

  Set Flds = iConf.Fields With Flds .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") _ = "Fill in your SMTP server here" .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 .Update End With