SSIS 脚本任务,从 Outlook 2007 中提取附件
这是“从 Outlook 2003 中提取邮件和附件”的替代方案。
简介
根据我的经验,有很多客户每天/每月通过电子邮件发送数据,并且不愿意改变这种方式。 我想自动化这个过程,这样我就不需要每次收到邮件时手动将文件放到某个位置了。
我在网上搜索了解决方案,有一些可用的,但没有免费的。 而且免费的通常不支持 smtp。 所以当我看到参考代码时,我将其修改为我的脚本任务...
代码的作用
SSIS 脚本任务代码,用于下载用户 test@test.com 收到的 Outlook 附件,并将其保存到本地或网络文件位置 c:\Test,并将邮件移动到 Outlook 中的一个名为 test 的已完成文件夹。
要求
- SQL Server 2008 或 2012
- Visual Studio Premium(需要随 VS 2010 Premium 附带的 MS SDK)
- Outlook(在 2007 和 2010 上测试过)
限制
- 当遇到会议邀请时会失败(仅用 Outlook 2007 测试过)
- 在生产环境中,不得不使用具有主邮箱的 AD 帐户,而不是服务帐户。
- 需要在服务器上安装 Outlook
使用代码
- 在安装了 SSIS 的机器上安装 Outlook 并设置 Outlook 邮件。
- 创建脚本任务,脚本语言:Microsoft Visual Basic 2008
- 添加 Microsoft Outlook 引用
- 替换脚本代码为以下内容 - 编辑 test@tester.com 和 c:\test\
- 运行,希望一切顺利。
VS 2008
编辑脚本任务 -> 数据源 -> 添加新的数据源 -> 对象 -> 下一步 -> 添加引用 -> COM -> Microsoft Outlook 12.0 对象库
VS 2010
编辑脚本任务 -> 项目 -> 添加引用... -> COM -> Microsoft Outlook 12.0 对象库
Imports System
Imports System.Data
Imports System.Reflection
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Core
<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
<System.CLSCompliantAttribute(False)> Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum
Public Sub Main()
Dim oApp As Outlook.Application = New Outlook.Application() ' Create Outlook application.
Dim oNS As Outlook.NameSpace = oApp.GetNamespace("mapi") ' Get Mapi NameSpace.
Dim Attachment As Outlook.Attachment
Dim FileName As String
'oNS.Logon('oNS.Logon("Username", "Password", False, True) ' TODO:
' Get Messages collection of Inbox
Dim oInbox As Outlook.MAPIFolder = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
Dim oItems As Outlook.Items = oInbox.Items
'*** CHANGE OUTLOOK DESTINATION FOLDER
Dim oDestFolder As Outlook.MAPIFolder = oInbox.Folders("test")
Console.WriteLine("Total : " & oItems.Count)
' Get unread e-mail messages.
'oItems = oItems.Restrict("[Unread] = true")
Console.WriteLine("Total Email : " & oItems.Count)
' Loop each unread message.
Dim oMsg As Outlook.MailItem
Dim i As Integer
Dim j As Integer
i = 0
j = 1
For i = 1 To oItems.Count
oMsg = oItems.Item(i)
'MessageBox.Show(oMsg.SenderName, "Sender Name")
'MessageBox.Show(oMsg.Attachments.Count, "# of Attachments")
'*** ADD YOUR SENDER HERE (use @ not A)
If (oMsg.SenderName = "testAtest.com") Then
For Each Attachment In oMsg.Attachments
MessageBox.Show(Attachment.FileName)
'*** CHANGE YOUR DIRECTORY HERE
FileName = "c:\Test\" & Attachment.FileName
Attachment.SaveAsFile(FileName)
j = j + 1
Next
oMsg.Move(oDestFolder)
End If
i = i + 1
Next
' Log off.
oNS.Logoff()
' Clean up.
oApp = Nothing
oNS = Nothing
oItems = Nothing
oMsg = Nothing
Dts.TaskResult = ScriptResults.Success
End Sub
End Class