我有以下代码,我的目标是使用文本文件作为模板,将自动电子邮件发送到Excel文档中的人员列表:
Set objMessage = CreateObject("CDO.Message")
Set app = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In fso.GetFolder("F:\Billing_Common\autoemail").Files
If LCase(fso.GetExtensionName(f)) = "xls" Then
Set wb = app.Workbooks.Open(f.Path)
set sh = wb.Sheets("Auto Email Script")
row = 2
email = sh.Range("A" & row)
subject = "Billing"
LastRow = sh.UsedRange.Rows.Count
For r = row to LastRow
If App.WorkSheetFunction.CountA(sh.Rows(r)) <> 0 Then
objMessage.Subject = "Billing: Meter Read"
objMessage.From = "billing@energia.ie"
objMessage.To = email
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim emailText
Set emailText = fso.OpenTextFile("F:\Billing_Common\autoemail\Script\Email.txt", ForReading)
BodyText = emailText.ReadAll
objMessage.TextBody = emailText
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = CdoSendUsingPort
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "ADDRESS OF SERVER HERE"
'Server port
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update
objMessage.Send
End if
Next
emailText.Close
Set emailText = Nothing
Set fso = Nothing
wb.Close
End If
Next
它在objMessage.TextBody上抛出一个错误,说类型不匹配。如果有人能帮助我,我将不胜感激!
谢谢!
答案 0 :(得分:2)
要发送内嵌图片,您需要创建一个HTMLBody
而不是TextBody
,并在图片上添加RelatedBodyPart
(请参阅here):
Set msg = CreateObject("CDO.Message")
...
msg.HTMLBody = "<html>" & vbLf & _
"<head><title>Test</title></head>" & vbLf & _
"<body><p><img src='foo.jpg'></p></body>" & vbLf & _
"</html>"
msg.AddRelatedBodyPart "C:\path\to\your.jpg", "foo.jpg", 0
答案 1 :(得分:0)
在行BodyText = emailText.ReadAll
之后,你应该分配那个,而不是文件(&#34; emailText&#34;是TextFile
{{1}前一行的Open
编辑),这就是为什么它抱怨类型不匹配...
所以只需将fso
替换为objMessage.TextBody = emailText
,它应该有用......