Set objEmail = CreateObject("CDO.Message")
objEmail.From = "helpdesk@fabrikam.com"
objEmail.To = "administrator@fabrikam.com"
objEmail.Subject = "Server down"
objEmail.Textbody = "Server1 is no longer accessible over the network."
objEmail.Configuration.Fields.Item _
("https://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
("https://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"smtpmailer"
objEmail.Configuration.Fields.Item _
("https://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
今天我們不會對這個指令碼作詳細的解釋;如需此處所使用之個別屬性的概觀,請參閱 Microsoft Windows 2000 指令碼指南 (英文)。您可能輕易就能瞭解 From、To、Subject 及 Textbody 屬性。有些 URIs (例如,https://schemas.microsoft.com/cdo/configuration/sendusing) 是重複使用的程式碼,一般來說保留原樣就好;大多數狀況中,您唯一要變更的是 smtpserver。在我們的範例程式碼中,已經參照了名為 smtpmailer 的 SMTP 郵件伺服器;您需要將名稱取代為「您的」SMTP 郵件伺服器。
此外,這些 URIs 困擾了許多人:他們納悶為什麼要連線到 Microsoft 才能傳送電子郵件呢?事實上,您不是真正連線到 Microsoft;這些 URIs 只是屬性。為什麼它們的參照方式是如此呢?老實說,我們也不知道。不過不要緊張。您的郵件不會路由傳送到 Microsoft,這裡也沒有人會閱讀您的郵件。請相信我們,我們光處理自己的郵件就夠麻煩了,不會有空去閱讀別人的郵件。
現在,要怎麼將附件加入這封電子郵件中呢?這只需要多一行程式碼,差不多類似這一行就可將 C:\Scripts\Output.txt 檔案附加到電子郵件中:
objEmail.AddAttachment "C:\Scripts\Output.txt"
就是這樣;將這行程式碼加入指令碼中,您就有自己的附件了。完整的指令碼看起來像這樣:
Set objEmail = CreateObject("CDO.Message")
objEmail.From = "helpdesk@fabrikam.com"
objEmail.To = "administrator@fabrikam.com"
objEmail.Subject = "Server down"
objEmail.Textbody = "Server1 is no longer accessible over the network."
objEmail.AddAttachment "C:\Scripts\Output.txt"
objEmail.Configuration.Fields.Item _
("https://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
("https://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"smtpmailer"
objEmail.Configuration.Fields.Item _
("https://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
值得注意的是,有許多人詢問我們如果 SMTP 伺服器需要驗證時,該怎麼傳送電子郵件。說實話,這是個很難回答的問題,因為 (基於各種理由) 我們無法測試這個案例。不過,將使用者名稱及密碼加入指令碼中會是個好的開始:
objEmail.Configuration.Fields.Item _
("https://schemas.microsoft.com/cdo/configuration/sendusername") = "fabrikam\kenmyer"
objEmail.Configuration.Fields.Item _
("https://schemas.microsoft.com/cdo/configuration/sendpassword") = "&gr54#wgha"
前面的程式碼讓您以 fabrikam\kenmyer 身分及 &gr54#wgha 為密碼登入 SMTP 伺服器。請注意,這會以純文字格式傳送使用者名稱及密碼。因此,您可能不會想使用 Administrator 帳戶傳送電子郵件。相反的,建立有權傳送電子郵件 (但權限很小,除非有別的權限) 的使用者帳戶,並使用該帳戶登入。如需詳細資訊,請查看 MSDN 上的正式 CDO 說明文件 (英文)。 |