2016-05-13 69 views
2

我试图用附件发送电子邮件:带附件..VBA代码发送电子邮件

我的代码:

Sub SendEmailUsingGmail() 
Dim Text As String 
Dim Text2 As String 
Dim i As Integer 
Dim j As Integer 
Dim NewMail As CDO.Message 

Set NewMail = New CDO.Message 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True 

'Make SMTP authentication Enabled=true (1) 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 

'Set the SMTP server and port Details 
'To get these details you can get on Settings Page of your Gmail Account 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com" 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 

'Set your credentials of your Gmail Account 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "[email protected]" 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "********" 

'Update the configuration fields 
NewMail.Configuration.Fields.Update 

'Set All Email Properties 

With NewMail 
    .Subject = "Test Mail" 
    .From = "[email protected]" 
    For i = 1 To 2 
     Text = Cells(i, 1).Value 
     Text2 = Cells(i, 2).Value 
     .To = Text 
     .BCC = "" 
     .TextBody = "" 
     .AddAttachment Text2 
     Text2 = Null 
     .Send 
    Next i 

End With 

End Sub 

它读取从第一栏和第二栏我的电子邮件地址共享附件的地址。 当它通过电子邮件发送最后一个用户时,它将所有附件从最上面一行附加到附件上。 e.g:

[email protected] C:\Users\sprasad\Desktop\Test.docx   
[email protected]  C:\Users\sprasad\Desktop\Test2.docx 

所以对于SHA @ GWU它会发出两个文档测试和Test2的。

我只想附加sha @ gwu的test2文档。 我的代码怎么了?

+1

你'结束With'和'接下来i'是走错了路周围 –

+0

@Macro ...你可以PLZ解释...我是新来的VBA和这是我的第三个代码.... – Shank

+0

我不知道什么是要解释 - 交换'结束与'和'下一个我... ...因为它代表应该代码shouldn甚至不会编译,所以不知道你如何运行它。 –

回答

0

加入这一行...

With NewMail 
    .Subject = "Test Mail" 
    .From = "[email protected]" 
    For i = 1 To 2 

    Text = Cells(i, 1).Value 
    Text2 = Cells(i, 2).Value 
    .To = Text 
    .BCC = "" 
    .TextBody = "" 
    .Attachments.DeleteAll  ' <-------- 
    .AddAttachment Text2 
    Text2 = Null 
    .Send 
    Next i 

End With 

End Sub 
0

改成这样

For i = 1 To 2 

Set NewMail = New CDO.Message 

'// Rest of code here... 

With NewMail 
    .Subject = "Test Mail" 
    .From = "[email protected]" 

    Text = Cells(i, 1).Value 
    Text2 = Cells(i, 2).Value 
    .To = Text 
    .BCC = "" 
    .TextBody = "" 
    .AddAttachment Text2 
    Text2 = Null 
    .Send 

End With 

Next 
+0

这工作.... thnx – Shank

+0

不要忘了标记为答案,如果它通过点击左边的勾号帮助 –

相关问题