从Excel VBA发送电子邮件 - 名称无法识别

时间:2014-07-05 14:18:39

标签: excel vba excel-vba outlook

我使用以下代码使用outlook发送来自excel的电子邮件:

Private Sub SendEmail()

  Set OutlookApp = CreateObject("Outlook.Application")
  Set OlObjects = OutlookApp.GetNamespace("MAPI")
  Set newmsg = OutlookApp.CreateItem(olMailItem)

  newmsg.Recipients.Add ("name@domain.com; name2@domain.com; name3@domain.com")

  newmsg.Subject = "Test Mail"

  newmsg.Body = "This is a test email."

  'newmsg.Display

  newmsg.Send

End Sub

代码工作正常,但在尝试发送电子邮件时,我从Outlook收到以下错误:

ErrorScreen http://im58.gulfup.com/GRENlB.png

奇怪的是,如果我将新消息打开两三分钟,名称将自动得到解决:

Working http://im74.gulfup.com/qmOYGQ.png

然而,这并不适合我,因为我不希望在邮件发送之前显示该邮件。我希望在运行代码后立即发送它。

任何建议或解决方法都将受到赞赏。

作为旁注:我尝试启用"允许逗号作为电子邮件分隔符" outlook中的选项,然后使用逗号而不是分号,但我仍然面临同样的问题。

更新

以下是工作代码,根据 Dmitry Streblechenko 答案:

Private Sub SendEmail()

    Dim OutApp As Object
    Dim OutMail As Object
    Dim strbody As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OlObjects = OutApp.GetNamespace("MAPI")
    Set OutMail = OutApp.CreateItem(olMailItem)

On Error Resume Next
    With OutMail
        .To = ("name@domain.com; name2@domain.com; name3@domain.com")
        .Subject = "Test Mail"
        .Body = "This is a test email."
        '.Display
        .Send
    End With

End Sub

2 个答案:

答案 0 :(得分:7)

您无法将多个名称传递给Recipients.Add - 您将获得名为" name@domain.com的单个收件人; name2@domain.com; name3@domain.com" ;.为每个收件人调用Recipients.Add 3次或设置To属性 - 它将解析多个名称。

答案 1 :(得分:2)

您应该添加对ResolveAll的通话,以明确解决所有收件人问题。 否则,在短暂的等待期后自动完成解决。

示例:

Sub CheckRecipients()      
 Dim MyItem As Outlook.MailItem 
 Dim myRecipients As Outlook.Recipients 
 Dim myRecipient As Outlook.Recipient 

 Set myItem = Application.CreateItem(olMailItem)      
 Set myRecipients = myItem.Recipients 

 myRecipients.Add("Aaron Con")      
 myRecipients.Add("Nate Sun")      
 myRecipients.Add("Dan Wilson") 

 If Not myRecipients.ResolveAll Then      
     For Each myRecipient In myRecipients      
        If Not myRecipient.Resolved Then      
           MsgBox myRecipient.Name      
        End If      
     Next      
 End If      
End Sub

here复制的代码。