简体   繁体   中英

VBScript to send email via SMTP

I have the following code, my goal is to send automatic emails to a list of people in an excel document, using a text file as a template:

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

It throws an error at the objMessage.TextBody, saying type mismatch. If anyone could help me it would be much appreciated!

Thanks!

For sending inline images you need to create an HTMLBody instead of a TextBody and add a RelatedBodyPart with the image (see 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

After the line BodyText = emailText.ReadAll , you ought to assign that , and not the file ("emailText" is the TextFile that was Open ed by fso on the previous line), that's why it's complaining about a Type Mismatch...

So just replace objMessage.TextBody = emailText with objMessage.TextBody = BodyText and it should work...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM