Excel VBA - 循环发送电子邮件 - 仅发送一封电子邮件

时间:2021-05-08 21:03:21

标签: vba sendgrid cdo.message

我从 stackoverflow 上的其他线程之一获得了此代码。我稍微修改了一下。

这适用于发送一封电子邮件。但是,当我在循环中使用此代码时,它只执行最后一封电子邮件。我之前没有使用过 CDO.Message、CDO.Config 和 Fields。知道为什么会这样吗?

'Part of a procedure
   eBody = "html body"
   With shTemp
      For i = 2 To lastRow
         toEmail = "emailAddress"
         eAttachment1 = "path1"
         eAttachment2 = "path2"
         
         sendEmail = emailPDFs(toEmail, eBody, eAttachment1, eAttachment2)
      Next i
   End With
'=========

Function emailPDFs(toEmail As String, eBody As String, eAttachment1 As String, eAttachment2 As String)
    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    
   Set Flds = iConf.Fields
   With Flds
       .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
       .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
                      = "smtp.sendgrid.net"
       .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 587
       .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
       .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "xxxx"
       .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "xxxx"
       .Update
   End With

    With iMsg
        Set .Configuration = iConf
        .To = toEmail
        .From = "..."
        .Subject = "Test email"
        .AddAttachment eAttachment1
        .AddAttachment eAttachment2
        .htmlBody = eBody
        .send    
    End With
        
End Function

0 个答案:

没有答案