-->
顯示包含「vba」標籤的文章。顯示所有文章
顯示包含「vba」標籤的文章。顯示所有文章

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.

Outlook+VBA: How to delete older deleted email after n days automatically on schedule?

Here's coding is only for selecting a specific folder such as "Deleted Items" and check the date whether is older than n days, for example is 14 days, then delete it permanently.

Reference, if you don't know : How to create VBA function, Outlook rule and enable macros in Outlook?

1) Press Alt+F11 to open VBA to create a function on Outlook.

Example 1:
A simple way to delete all type of emails which are under “Deleted Items" folder and the Last Modifcation Time (DateTime) older than 14 days.
Sub CleanupDeletedEmail(Item As Outlook.MailItem)
    Dim DelItems As Outlook.Items
    Dim OlderDay As Integer
    
    OlderDay = 14

    Set DelItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderDeletedItems).Items
    
    For i = DelItems.Count To 1 Step -1
       If DateDiff("d", DelItems.Item(i).LastModificationTime, Date) >= OlderDay Then
            DelItems.Item(i).Delete
       End If
    Next

    Set DelItems = Nothing
End Sub
Tips:
1. You can also change the folder from Deleted Items “olFolderDeletedItems" to another such as Inbox “olFolderInbox".
2. As email that received will include non-email type, for example delivery email error that sent by outlook server or task, which does not have SentOn date, so using “LastModificationTime" instead of “SentOn".


Example 2:
Sending an email if there is any error found during deleting. Besides, if item type is email then check the SentOn date otherwise using LastModificationTime.
Sub CleanupDeletedEmail(Item As Outlook.MailItem)
    On Error GoTo ErrHandler
    
    Dim DelItems As Outlook.Items
    Dim OlderDay As Integer
    Dim IsDel As Boolean
    Dim sRptToEmailAddr As String
    
    OlderDay = 14
    sRptToEmailAddr = "name@domain.com"    

    Set DelItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderDeletedItems).Items
    
    For i = DelItems.Count To 1 Step -1
        IsDel = False    

        If DelItems.Item(i).Class = olMail Then
            If DateDiff("d", DelItems.Item(i).SentOn, Date) >= OlderDay Then
                IsDel = True
            End If
        ElseIf DateDiff("d", DelItems.Item(i).LastModificationTime, Date) >= OlderDay Then
            IsDel = True
        End If
        
        If IsDel = True Then DelItems.Item(i).Delete
    Next
    
GoTo Finally
ErrHandler:
    Call CreateNewMessage("Error: " + Item.Subject, sRptToEmailAddr, Err.Description)
Finally:
    Set DelItems = Nothing
End Sub

Sub CreateNewMessage(pSubject As String, pTo As String, pBody As String)
    Dim objMsg As MailItem    
    Set objMsg = CreateItem(olMailItem)
    With objMsg
        .Subject = pSubject
        .To = pTo
        .Body = pBody
        
        .Send
    End With

    Set objMsg = Nothing
End Sub

2) Save and exit VBA.

3) Create a new rule on Outlook.
3.1) Start from a blank rule: Select "Apply rule on messages I receive" -> press Next
3.2) Which condition(s) do you want to check? Select "with specific words in the subject"
3.3) Use mouse to click "specific words" in "Edit the rule description" box, and input "Call Cleanup Deleted Email". -> press "Add" -> press "OK".
3.4) What do you want to do with the message? Select "delete it" and "run a script".
3.5) Use mouse to click "run a script" in "Edit the rule description" box, and select "Project1.ThisOutlookSession.CleanupDeletedEmail". -> press Next.
3.6) Press Next to ignore "Are there any exceptions?".
3.7) Assign a name for this rule: Call Cleanup Deleted Email.
3.8) Press Finished.

rule

The action of this rule: When new email arrived which the subject is "Call Cleanup Deleted Email" then delete this email and run the script "CleanupDeleteEmail".

You can now to send an email with the subject is "Call Cleanup Deleted Email" to this account for checking whether the rule can call the script and delete the email which the date is older than 14 days correctly.

Using below tutorial link to create a Task Scheduler and send "Call Cleanup Deleted Email" email periodically.
Task Scheduler: Another way to send an email via SMTP using script

Below is an example to kick-off the task on 12:05am everyday. There are many options such as Daily, Weekly, Monthly or Repeating for you selection, so you can assign what you want in Trigger.
task

Outlook+VBA: How to delete Auto-forwarded emails using outlook rule and VBA?

There is not condition for Auto-forwarded when you try to create a new rule in Outlook, so you have to run a script when an email arrives.

1) Press Alt+F11 to open VBA (VbaProject.OTM) on Outlook 2010.
2) Create a procedure. Copy and paste below coding in your VBA.
Sub DeleteAutoForwardedEmail(Item As Outlook.MailItem)
   If Item.AutoForwarded Then
      Item.Delete
   End If
End Sub
vba
3) Save and exit VBA.

4) Create a new rule on Outlook 2010.
5) Start from a blank rule: Select “Apply rule on messages I receive” -> press Next
6) Which condition(s) do you want to check? Select nothing or “on this computer only” -> press Next.
7) What do you want to do with the message? Select “run a script”.
8) Use mouse to click “run a script” in “Edit the rule description” box, and select “Project1.ThisOutlookSession.DeleteAutoForwardedEmail”. -> press Next.
9) Press Next to ignore “Are there any exceptions?”.
10) Assign a name for this rule: Delete AutoForwarded Email.
11) Press Finished.

rule



Before to run the script, you need to enable macros in Outlook.

1) File -> Options -> Trust Center -> Trust Center Settings
2) Macro Setting -> Select "Enable all macros (not recommended; potentially dangerous code can run)".
3) Press OK and re-start Outlook.

enablemacro