2015年10月26日星期一

Task Scheduler+VBA: Send an email via SMTP using VB script

Task Scheduler provides "Send an e-mail" function, but it does not work with authentication. To solve the problem, I created a script with arguments for sending an email using "Start a program" action instead of "Send an e-mail" in Task Scheduler.

1) Copy and save below script in your computer. For example: save file in D:\script\ and named "SendEmail.vbs".
'==============================================================================
'=== Send Email using VBS Script
'===    arg1: Email Subject
'===    arg2: Email From
'===    arg3: Email To
'===    arg4: Email Text Body
'==============================================================================

SET args = WScript.Arguments
SET objEmail = CreateObject("CDO.Message")
SET objEmlConfig = objEmail.Configuration

DIM emlSubject
DIM emlFrom
DIM emlTo
DIM emlBody

emlSubject = args.Item(0)
emlFrom = args.Item(1)
emlTo = args.Item(2)
emlBody = args.Item(3)


WITH objEmlConfig.Fields
    .Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2      ' 2 = using SMTP
    .Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.server"      ' your smtp server id
    '.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    .Update
END WITH

WITH objEmail
    .Subject = emlSubject
    .From = emlFrom
    .To = emlTo

    .TextBody = emlBody
END WITH

' send email
objEmail.Send

SET objEmlConfig = nothing
SET objEmail = nothing
Remember to change the "smtp.server" as your SMTP Server.

2) Create a Task in Task Scheduler.
2.1) In General page, input the name of task.
2.2) In Triggers page, create a new trigger and set "Begin the task" is "On a schedule".
2.3) In Actions page, create a new action and set "Action" is "Start a program".
2.3.1) Set "Program/script" is "D:\script\SendEmail.vbs"
2.3.2) Set "Add arguments:" is "send email from vbs" "sendfrom" "sendto" "email_body". Remember to change the "sendfrom" and "sendto" as your email address.
2.3.3) Set "Start in" is "D:\script\".
2.4) Press OK to save.
schaction

You can try to run the task in Task Scheduler Library.

沒有留言:

發佈留言