2013-07-03 83 views
1

發送電子郵件,我有下面的代碼,我的目標是發送自動電子郵件到人的Excel文檔列表中,使用文本文件作爲模板:VBScript來通過SMTP

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 = "[email protected]" 
    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

我現在工作,但不能讓它使用該文本文件作爲模板。 –

+0

現在所有工作都正在進行,但是有誰知道如何添加圖像? –

+0

作爲附件?或者你想編寫HTML郵件? –

回答

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 
0

BodyText = emailText.ReadAll後,你應該分配,而不是該文件(「emailText」是TextFileOpen在前一行中由fso編輯),這就是爲什麼它抱怨類型不匹配...

所以,只需更換objMessage.TextBody = emailTextobjMessage.TextBody = BodyText,它應該工作...