分类目录归档:ASP & VB(J)Script

ASP & VB(J)Script

Modify an SMTP Service Property

ADSI:
strComputer = "LocalHost"

Set objIIS = GetObject("IIS://" & strComputer & "/SMTPSVC/1")
objIIS.FullyQualifiedDomainName = "stmp.517sou.net"
objIIS.SetInfo

#Wscript.Echo "OK!"

cscript.exe c:\inetpub\AdminScripts\adsutil.vbs set /Smtpsvc/1/FullyQualifiedDomainName "stmp.517sou.net"

PowerShell & WMI

Set-ExecutionPolicy RemoteSigned
function Configure-SMTPService ([string]$incomingEMailDomainName, [int]$incomingEMailMaxMessageSize)
{
       Write-Host -Foregroundcolor White ” -> Changing the start-up type of SMTP service to ‘Automatic’…”
       Set-Service “SMTPSVC” -StartupType Automatic -ErrorAction SilentlyContinue
       if ($?)
       {
             Write-Host -Foregroundcolor Green ” [OK] Successfully changed startup type.”
       }
       else
       {
             Write-Host -Foregroundcolor Red ” [Error] Unable to change startup type.”
             Exit
       }
       
       Write-Host -Foregroundcolor White ” -> Starting SMTP service…”
       Start-Service “SMTPSVC” -ErrorAction SilentlyContinue
       
       if ($?)
       {
             Write-Host -Foregroundcolor Green ” [OK] Service successfully started.”
       }
       else
       {
             Write-Host -Foregroundcolor Red ” [Error] Unable to start service.”
             Exit
       }
      
       # Ascriptomatic is a great tool to explorefor exploring WMI namespace is scriptomatic: 
       # http://www.microsoft.com/en-us/download/details.aspx?id=12028
       Write-Host -Foregroundcolor White ” -> CreatingCreate incoming SMTP domain…”
       
       # First create a new smtp domain. The path ‘SmtpSvc/1’ is the first virtual SMTP server. If you need to modify another virtual SMTP server
       # change the path accordingly.
       try
       {
             $smtpDomains = [wmiclass]‘root\MicrosoftIISv2:IIsSmtpDomain’
             $newSMTPDomain = $smtpDomains.CreateInstance()
             $newSMTPDomain.Name = “SmtpSvc/1/Domain/$incomingEMailDomainName“
             $newSMTPDomain.Put()  | Out-Null
             Write-Host -Foregroundcolor Green ” [OK] Successfully created incoming email domain.”
       }
       catch
       {
             Write-Host -Foregroundcolor Red ” [Error] Unable to create incoming email domain.”
             Exit
       }
      
       Write-Host -Foregroundcolor White ” -> Configuring incoming SMTP domain…”
   
       try
       {
             # Configure the new smtp domain as alias domain
             $smtpDomainSettings = [wmiclass]‘root\MicrosoftIISv2:IIsSmtpDomainSetting’
             $newSMTPDomainSetting = $smtpDomainSettings.CreateInstance()
 
             # Set the type of the domain to “Alias”
             $newSMTPDomainSetting.RouteAction = 16
 
             # Map the settings to the domain we created in the first step
             $newSMTPDomainSetting.Name = “SmtpSvc/1/Domain/$incomingEMailDomainName“
             $newSMTPDomainSetting.Put() | Out-Null
             Write-Host -Foregroundcolor Green ” [OK] Successfully configured incoming email domain.”
       }
       catch
       {
             Write-Host -Foregroundcolor Red ” [Error] Unable to configure incoming e-mail domain.”
             Exit
       }
       Write-Host -Foregroundcolor White ” -> Configuring virtual SMTP server…”

       try
       {
             $virtualSMTPServer = Get-WmiObject IISSmtpServerSetting -namespace “ROOT\MicrosoftIISv2” | Where-Object { $_.name -like “SmtpSVC/1” }
             
             # Set maximum message size (in bytes)
             $virtualSMTPServer.MaxMessageSize = ($incomingEMailMaxMessageSize * 1024)

             # Disable session size limit
             $virtualSMTPServer.MaxSessionSize = 0

             # Set maximum number of recipients
             $virtualSMTPServer.MaxRecipients = 0

             
             # Set maximum messages per connection
             $virtualSMTPServer.MaxBatchedMessages = 0
             $virtualSMTPServer.Put() | Out-Null
             Write-Host -Foregroundcolor Green ” [OK] Successfully configured virtual SMTP server.”
       }
       catch
       {
             Write-Host -Foregroundcolor Red ” [Error] Unable to configure virtual SMTP server.”
             Exit
       }
}
Configure-SMTPService “sp.mydomain.local” 10240

Puppet部署:
configWinSMTPSVC.vbs

strComputer = "LocalHost"
 
Set objIIS = GetObject("IIS://" & strComputer & "/SMTPSVC/1")
Wscript.Echo "FullyQualifiedDomainName(Before): " & objIIS.FullyQualifiedDomainName
strFQDN = Trim(objIIS.FullyQualifiedDomainName)
If Instr(strFQDN,"517sou.net") = 0 Then
	objIIS.FullyQualifiedDomainName = "smtp.517sou.net"
	objIIS.SetInfo
End If
Wscript.Echo "FullyQualifiedDomainName(After): " & objIIS.FullyQualifiedDomainName
class configWinSMTPSVC {
    file { 'C:/Windows/Temp/configWinSMTPSVC.vbs':
    ensure => 'file',
	alias  => "configWinSMTPSVCvbs",
    source_permissions  => ignore,
    group  => 'Administrators',
	source => "puppet://puppet.zzy.com/files/windows/smtpsvc/configWinSMTPSVC.vbs",
  }
  exec { 'exec-configWinSMTPSVC':
    path      => $::path,
    command   => 'cmd.exe /c cscript.exe //Nologo C:/Windows/Temp/configWinSMTPSVC.vbs',
	require   => File['configWinSMTPSVCvbs'],
  }
}

获取Windows管理员用户名及对应的SID

GetAdminName.vbs:

'''''Code Start '''''
Wscript.Echo GetAdminName

Function GetAdminName 
	Set objNetwork = CreateObject("Wscript.Network") 	'get the current computer name
	objComputerName = objNetwork.ComputerName

	Set objwmi = GetObject("winmgmts:{impersonationLevel=impersonate}!//" & objComputerName)
	qry = "SELECT * FROM Win32_Account where Domain = '" & cstr(objComputerName) & "'" 'set query, making sure to only look at local computer

	For Each Admin in objwmi.ExecQuery(qry)
		if (left(admin.sid, 6) = "S-1-5-" and right(admin.sid,4) = "-500") then 	'look for admin sid
			GetAdminName = admin.name
		end if
	next
End Function

'''''Code End'''''

在.bat中获取.vbs返回值
GetAdminName.bat

@echo off
for /f "delims=" %%x in ('cscript //nologo t.vbs') do (
    set sFileName=%%x
)
echo %sFileName%
REM pause.

命令行查询用户对应的SID

C:\Users\Administrator>wmic useraccount where "SID like 'S-1-5-%-500'" get sid
SID
S-1-5-21-2837057897-1460117072-2570820871-500

E:\temp>wmic useraccount where "SID like 'S-1-5-%-%'" get caption,sid
Caption SID
SHANE-WORKPLACE\Administrator S-1-5-21-4246277841-3966888941-2683127511-500
SHANE-WORKPLACE\DefaultAccount S-1-5-21-4246277841-3966888941-2683127511-503
SHANE-WORKPLACE\Guest S-1-5-21-4246277841-3966888941-2683127511-501
SHANE-WORKPLACE\Shane.Wan S-1-5-21-4246277841-3966888941-2683127511-1001

FTP Upload and FTP Download with VBScript

While googling around the other day I noticed that lots of people are searching for a way to FTP files with VBScript. After looking for a while at the solutions to do this, it was clear that no real easy, free way of FTP uploading and downloading files was currently available. There are downloadable components that would present a programable API. But these are costly, and you’d have to install them. So seeing the need I decided to whip up a couple of functions that would preform some basic uploading and downloading. 继续阅读

VB中通过WMI控制DNS服务器,可在ASP中调用

VB中通过WMI控制DNS服务器,可在ASP中调用

在VB中要使用Scripting API for WMI,必须引用 Microsoft WMI Scripting V1.1 Library

下面介绍Scripting API For WMI的几个对象

SWbemLocator——用于取得SWbemServices对象,他代表了本地或远程计算机上名字空间的一个连接。
SWbemService——代表名字空间的一个连接,可用于处理它的部件
SWbemObject——代表一个单独的类定义或一个对象实例
SWbemOjbectSet——包括SWbemObject的集合 继续阅读

Some examples of scripting of IIS using ADSI, WMI from VB and C# including the new Microsoft.Web.Administration namespace

Below are some simple examples of how to talk to IIS via ADSI, WMI and the new IIS 7 only .NET Managed Provider.

The IIS ADSI Provider

The IIS ADSI provider exposes COM Automation objects that you can use within command-line scripts, ASP pages, or custom applications to change IIS configuration values stored in the IIS metabase. IIS ADSI objects can be accessed and manipulated by any language that supports automation, such as Microsoft® Visual Basic® Scripting Edition (VBScript), Microsoft JScript®, Perl, Microsoft Active Server Pages (ASP), Visual Basic, Java, or Microsoft C++.

继续阅读

Sending E-Mail Without Installing the SMTP Service

Microsoft® Windows® 2000 Scripting Guide

The script shown in Listing 17.23 can be used as long as the SMTP service is installed on the computer where the script is running. Obviously, this poses a problem: Most likely, you do not want the SMTP service to be installed and running on every one of your computers. 继续阅读

JMail相关实例代码

<%@LANGUAGE="VBSCRIPT" %>
<HTML>
<BODY>
<%

'*************************************************
'*                                               *
'*   Produced by Dimac                           *
'*                                               *
'*   More examples can be found at                  *
'*   http://tech.dimac.net                       *
'*                                               *
'*   Support is available at our helpdesk        *
'*   http://support.dimac.net                    *
'*                                               *
'*   Our main website is located at              *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************<!--more-->



    ' Example on how to use queueing
    
    ' The message is set up as usual..
    set Message = Server.CreateObject( "JMail.Message" )

    Message.From = "myEmail@mydomain.com"
    Message.Subject = "Testing"
    Message.Body = "This is a test mail"
    Message.AddRecipient "myRecipient@hisdomain.com","A Name"

    ' Instead of using the Send() method, we use nq 
    ' The email will be placed in the mail queue and sent 
    ' as soon as the mailservice picks it up.
    ' We do not need to specify a mailserver, as the
    ' mailservice does all that for us.
    
    ' What we do need to do is to specify where the MS pickup
    ' directory is. If you are running w3 JMail on a 
    ' Windows 2000 server, this is not neccessary, otherwise
    
    ' Unless you are running windows 2000 on your webserver,
    ' you will need to specify where the MS pickup directory
    ' is (c:\inetpub\mailroot\pickup\).
    
    Message.MSPickupDirectory = "c:\inetpub\mailroot\pickup\"
    Message.nq
%>
</BODY>
</HTML>



<%
'*************************************************
'*                                               *
'*   Copyright (C) Dimac AB 2000                 *
'*   All rights reserved.                        *
'*                                               *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************


'-------------------------------------------------------------------------'
' This function iterates through the Recipients Object
' and formats the message's recipients
ReTo = ""
ReCC = ""

Sub getRecipients( )

  Set Recipients = msg.Recipients
  seperator = ", "

  For i = 0 To Recipients.Count - 1

     If i = Recipients.Count - 1 Then
        seperator = ""
     End If

     Set re = Recipients.item(i)
     If re.ReType = 0 Then
         ReTo = ReTo & re.Name & "&nbsp;(<a href=""mailto:"& re.EMail &""">" & re.EMail & "</a>)" & seperator
     else
        ReCC = ReTo & re.Name & "&nbsp;(<a href=""mailto:"& re.EMail &""">" & re.EMail & "</a>)" & seperator
     End If

  Next

End Sub


'-------------------------------------------------------------------------'
' This function iterates through the Attachments object,
' and saves the attachment to the server's disk.
' It also returns a nicely formated string with a
' link to the attachment.
Function getAttachments( )

  Set Attachments = msg.Attachments
  seperator = ", "

  For i = 0 To Attachments.Count - 1

     If i = Attachments.Count - 1 Then
        seperator = ""
     End If

     Set at = Attachments.Item(0)
     at.SaveToFile( "c:\EMail\attachments\" & at.Name )
     getAttachments =    getAttachments & "<a href=""/EMail/attachments/" & at.Name &""">" &_
                at.Name & "(" & at.Size  & " bytes)" & "</a>" & seperator
  Next

End Function


%>

<%@LANGUAGE="VBSCRIPT" %>
<HTML>
<BODY>
<%

'*************************************************
'*                                               *
'*   Produced by Dimac                           *
'*                                               *
'*   More examples can be found at                  *
'*   http://tech.dimac.net                       *
'*                                               *
'*   Support is available at our helpdesk        *
'*   http://support.dimac.net                    *
'*                                               *
'*   Our main website is located at              *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************

    Set jmail = Server.CreateObject("JMail.Message")

    jmail.AddRecipient "myRecipient@hisdomain.com", "Mr.Example"
    jmail.From = "me@mydomain.com"
    
    jmail.Subject = "Here's some graphics!"
    jmail.Body = "A nice picture if you can read HTML-mail."

    ' The return value of AddAttachment is used as a
    ' reference to the image in the HTMLBody.
    contentId = jmail.AddAttachment("c:\myCoolPicture.gif")

    ' As only HTML formatted emails can contain inline images
    ' we use HTMLBody and appendHTML
    jmail.HTMLBody = "<html><body><font color=""red"">Hi, here is a nice picture:</font><br>"
    jmail.appendHTML "<img src=""cid:" & contentId & """>"
    jmail.appendHTML "<br><br> good one huh?</body></html>"
    
    ' But as not all mailreaders are capable of showing HTML emails
    ' we will also add a standard text body
    jmail.Body = "Too bad you can't read HTML-mail."
    jmail.appendText " There would have been a nice picture for you"
    
    jmail.Send( "mailserver.mydomain.com" )
%>
</BODY>
</HTML>


<%@LANGUAGE="VBSCRIPT" %>
<HTML>
<BODY>
<%

'*************************************************
'*                                               *
'*   Produced by Dimac                           *
'*                                               *
'*   More examples can be found at                  *
'*   http://tech.dimac.net                       *
'*                                               *
'*   Support is available at our helpdesk        *
'*   http://support.dimac.net                    *
'*                                               *
'*   Our main website is located at              *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************

    ' Key information
    ' To validate a key we need a Message object, even if we
    ' do not intend to actually send an email.
    set jmail = Server.CreateObject( "JMail.Message" )

    ' Key identifiers supplied in a comma separated string.
    ' Valid identifiers are emailaddresses and hexadecimal key id's
    ' in the format 0xAABBCCDD as seen below
    ' No special order is needed.

    keyString = "kirne@dimac.net"

    ' Verifykeys returns true if all the supplied keys could be matched with a key in the local keyring.
     if jmail.VerifyKeys( keyString ) THEN
    
        ' KeyInformation return a PGPKeys collection with information for all the supplied keys.
          set keys = jmail.KeyInformation( keyString )
        Response.Write("Found keys for " & keyString & "<br>")
        Response.Write( "--------------------------------------------------------<br>")
        
        ' Iterate the PGPKeys collection
        For i = 0 To keys.Count-1
            Response.Write( "Key ID: " & keys.Item( i ).KeyID & " <br> " )
            Response.Write( "Username: " & keys.Item( i ).KeyUser & " <br> " )
            Response.Write( "Key created: " & keys.Item( i ).KeyCreationDate & " <br> " )
            Response.Write( "--------------------------------------------------------<br>")
        Next

    ELSE
        ' Verifykeys returnEd false, some unknown keys where supplied.
        Response.write("One or more invalid key(s):" & keyString )
    END IF

%>
</BODY>
</HTML>


<% @LANGUAGE="VBSCRIPT" %>
<html>
<body>
<%

'*************************************************
'*                                               *
'*   Produced by Dimac                           *
'*                                               *
'*   More examples can be found at                  *
'*   http://tech.dimac.net                       *
'*                                               *
'*   Support is available at our helpdesk        *
'*   http://support.dimac.net                    *
'*                                               *
'*   Our main website is located at              *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************

    ' First we will create a message object that will serve as a 
    ' template for the merge.
    ' The merge fields are marked with %% in the front and in the 
    ' end.
    ' Note how we use merge fields even in the addRecipient method
    
    set msgTemplate = Server.CreateObject( "JMail.Message" )
    
    msgTemplate.From = "me@myDomain.com"
    msgTemplate.FromName = "Mailinglist info!"
    
    msgTemplate.AddRecipient "%%EMail%%>", "%%Name%%"
    
    msgTemplate.Subject = "Hi %%Name%%"
    msgTemplate.Body = "Hello %%Name%%,  you are my favorite website visitor!"
    
    
    
    ' There, our message template is done. Next we create the mailmerge object.
    set mMerge = Server.CreateObject( "JMail.MailMerge" )
    
    ' Now, tell mailMerge to use the template we created earlier
    mMerge.MailTemplate = msgTemplate
    
    
    ' Now we have a few options on how to merge.
    ' We can do it manually or by specifying an ADO Recordset. 
    
    ' This is the manual way to do it.
    ' We specify each merge variable and give it a value.
    ' You will remember the mergeFields below from the template previously.
    mMerge.Item( "Name" ) = "Elvis Presley"
    mMerge.Item( "EMail" ) = "the.king@graceland.com"
    
    ' When the merge variables are finished, we replace all mergeFields
    ' in our template with the merge variables, using the expand() method.
    ' expand() returns a Message object.
    set msg = mMerge.Expand
    
    ' As usual we turn on logging and silent mode to handle possible errors.
    msg.Logging = true
    msg.silent = true
    
    if not msg.Send( "mail.myDomain.net" ) then
        Response.write "<pre>" & msg.log & "</pre>"
    else
        Response.write "Mailmerge successful and email sent succesfully!"
    end if  

    ' Ok, thats one email sent, however to understand the purpose
    ' of mailmerge, lets send another one.
    
    ' Set some new values in the merge variables
    mMerge.Item( "Name" ) = "Frank Sinatra"
    mMerge.Item( "EMail" ) = "old.blue.eyes@twinpalms.com"
    
    ' Now create us a new Message object with the new variables
    ' but use the same template. Let's reuse the msg variable as
    ' we no longer need the last email.
    set msg = mMerge.Expand
    
    ' As usual we turn on logging and silent mode to handle possible errors.
    msg.Logging = true
    msg.silent = true
    
    if not msg.Send( "mail.myDomain.net" ) then
        Response.write "<pre>" & msg.log & "</pre>"
    else
        Response.write "Mailmerge successful again and email sent succesfully!"
    end if 
    
    ' Thats it! One template, 2 emails.
%>
</body>
</html>


<% @LANGUAGE="VBSCRIPT" %>
<html>
<body>
<%

'*************************************************
'*                                               *
'*   Produced by Dimac                           *
'*                                               *
'*   More examples can be found at                  *
'*   http://tech.dimac.net                       *
'*                                               *
'*   Support is available at our helpdesk        *
'*   http://support.dimac.net                    *
'*                                               *
'*   Our main website is located at              *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************

    ' First we will create a message object that will serve as a 
    ' template for the merge.
    ' The merge fields are marked with %% in the front and in the 
    ' end.
    ' Note how we use merge fields even in the addRecipient method
    
    set msgTemplate = Server.CreateObject( "JMail.Message" )
    
    msgTemplate.From = "me@myDomain.com"
    msgTemplate.FromName = "Mailinglist info!"
    
    msgTemplate.AddRecipient "%%EMail%%>", "%%Name%%"
    
    msgTemplate.Subject = "Hi %%Name%%"
    msgTemplate.Body = "Hello %%Name%%,  you are my favorite website visitor!"    
    
    ' There, our message template is done. Next we create the mailmerge object.
    set mMerge = Server.CreateObject( "JMail.MailMerge" )
    
    ' Now, tell mailMerge to use the template we created earlier
    mMerge.MailTemplate = msgTemplate
    
    ' Before we start emailing thousands of recipients, we make testrun.
    ' The line below tells MailMerge to process only 10 recipients
    ' and to send the emails to "myEMail@company.com" instead.
    ' This way we can see if our template is as expected. When we
    ' are ready to go live, just remove the line below.
    mMerge.SetDebugMode "myEMail@company.com", 10 

    
    ' Okay lets do the merge. As we do an ADO resultset merge, we do not need to
    ' specify each merge variable.
    ' The myRS is assumed to hold a ADO recordset.
    
    ' If we didn't have to many recipients, we wouldn't have to enque the emails,
    ' instead we would have to specify the mailserver like this
    ' MailMerge.BulkMerge( myRS, false, "mail.myDomain.com" )'
    ' However, we will now enque it and therefore sets the second parameter to
    ' true and instead of supplying the mailserver address, we specify where
    ' our MS pickup directory is (if you run windows 2000 this is optional).
    
    ' The BulkMerge() method automatically sends/enques our emails, so we
    ' do not need to use the send() method.
    
    mMerge.BulkMerge myRS, true, "c:\inetpub\mailroot\pickup"
    
    ' Thats it! One template, a workload of emails.
%>
Mailmerge complete!
</body>
</html>


<% @ LANGUAGE = VBSCRIPT %>
<html>
<body>
<%

'*************************************************
'*                                               *
'*   Produced by Dimac                           *
'*                                               *
'*   More examples can be found at                  *
'*   http://tech.dimac.net                       *
'*                                               *
'*   Support is available at our helpdesk        *
'*   http://support.dimac.net                    *
'*                                               *
'*   Our main website is located at              *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************

    ' Create the JMail message Object
    set msg = Server.CreateOBject( "JMail.Message" )

    ' Set logging to true to ease any potential debugging
    ' And set silent to true as we wish to handle our errors ourself
    msg.Logging = true
    msg.silent = true

    ' Most mailservers require a valid email address
    ' for the sender
    msg.From = "test@mydomain.com"
    msg.FromName = "My Realname"
    
    ' Next we have to add some recipients.
    ' The addRecipients method can be used multiple times.
    ' Also note how we skip the name the second time, it
    ' is as you see optional to provide a name.
    msg.AddRecipient "recipient@hisDomain.com", "His Name"
    msg.AddRecipient "recipientelle@herDomain.com"    
    
    
    ' The subject of the message
    msg.Subject = "How you doin?"

    ' The body property is both read and write.
    ' If you want to append text to the body you can
    ' use JMail.Body = JMail.Body & "Hello world! "
    ' or you can use JMail.AppendText "Hello World! "
    ' which in many cases is easier to use.
    '
    ' Note the use of vbCrLf to add linebreaks to our email
    msg.Body = "Hello Jim" & vbCrLf & vbCrLf & "How's it going? ..."

    ' There.. we have now succesfully created our message. 
    ' Now we can either send the message or save it as a draft in a Database.
    ' To save the message you would typicly use the Message objects Text property
    ' to do something like this:
    '
    ' SaveMessageDraft( msg.Text )
    ' Note that this function call is only an example. The function does not
    ' exist by default, you have to create it yourself.
    
    
    ' If i would like to send my message, you use the Send() method, which
    ' takes one parameter that should be your mailservers address
    '
    ' To capture any errors which might occur, we wrap the call in an IF statement
    if not msg.Send( "mail.myDomain.net" ) then
        Response.write "<pre>" & msg.log & "</pre>"
    else
        Response.write "Message sent succesfully!"
    end if
    
    
    ' And we're done! the message has been sent.


%>
</body>
</html>


<%@LANGUAGE="VBSCRIPT" %>
<HTML>
<BODY>
<%

'*************************************************
'*                                               *
'*   Produced by Dimac                           *
'*                                               *
'*   More examples can be found at                  *
'*   http://tech.dimac.net                       *
'*                                               *
'*   Support is available at our helpdesk        *
'*   http://support.dimac.net                    *
'*                                               *
'*   Our main website is located at              *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************


    ' PGP signing
    ' Create the Message as usual
    set msg = Server.CreateObject( "JMail.Message" )

    msg.From = "anakin@tatooine.com"
    msg.Subject = "Hi!"
    msg.Body = "Hello dark forces!"


    msg.AddRecipient "emperor@coruscant.com", "palpatine"

    ' To sign an email, we set PGPsign to true
    msg.PGPSign = true

    ' We must choose a PGP key to sign with
    ' The key must reside in the local keyring.
    msg.PGPSignKey = "thechosenone@jedi.org"
    
    ' A passphrase is always needed to access a private key.
    ' It is NOT adviced to leave your key like this, anyone
    ' who have access to your ASP-files can read your key,
    ' however, to make this example we need to type it out.
    msg.PGPPassPhrase = "yoda"

    msg.Send "mymailserver.mydomain.com"
%>
</BODY>
</HTML>


<%@LANGUAGE="VBSCRIPT" %>
<HTML>
<BODY>
<%

'*************************************************
'*                                               *
'*   Produced by Dimac                           *
'*                                               *
'*   More examples can be found at                  *
'*   http://tech.dimac.net                       *
'*                                               *
'*   Support is available at our helpdesk        *
'*   http://support.dimac.net                    *
'*                                               *
'*   Our main website is located at              *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************

    ' PGP encryption
    ' The message is set up as usual...
    set msg = Server.CreateObject( "JMail.Message" )

    msg.From = "myEmail@mydomain.com"
    msg.Subject = "For your eyes only"
    msg.Body = "Top secret stuff for you."

    ' Set logging to true to ease any potential debugging
    ' And set silent to true as we wish to handle our errors ourself
    msg.Logging = true
    msg.silent = true

    ' An encryption key can be set as the third parameter to AddRecipient.
    ' This can be a comma separated string containing email addresses and
    ' hexadecimal key id's if more than one key are going to be used.
    ' The third parameter is optional and will default to the same value
    ' as the recipients email address, which in most cases are quite sufficient.

    ' msg.AddRecipient("myFriend@hisdomain.com", "A Name", "anEmail@mydomain.com, 0xFD43CD12, anotherEmail@mydomain.com" )

    msg.AddRecipient "myRecipient@hisdomain.com", "A Name"

    ' With PGPEncrypt set to true the email will be encrypted upon Send()
    msg.PGPEncrypt = true
    
    ' To capture any errors which might occur, we wrap the call in an IF statement
    if not msg.Send( "mail.myDomain.net" ) then
        Response.write "<pre>" & msg.log & "</pre>"
    else
        Response.write "Message sent succesfully and encrypted!"
    end if
%>
</BODY>
</HTML>


<% @LANGUAGE=VBSCRIPT %>
<%

'*************************************************
'*                                               *
'*   Produced by Dimac                           *
'*                                               *
'*   More examples can be found at                  *
'*   http://tech.dimac.net                       *
'*                                               *
'*   Support is available at our helpdesk        *
'*   http://support.dimac.net                    *
'*                                               *
'*   Our main website is located at              *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************


  Set pop3 = Server.CreateObject( "JMail.POP3" )

  pop3.Connect "username", "password", "mail.mydomain.com"

  Response.Write( "You have " & pop3.count & " mails in your mailbox!<br><br>" )

  if pop3.count > 0 then
    Set msg = pop3.Messages.item(1)     ' Note the first element of this array is 1
                                        ' since the POP3 server starts counting at 1
    ReTo = ""
    ReCC = ""
    
    Set Recipients = msg.Recipients
    separator = ", "
    
    ' We now need to get all the recipients,
    ' both normal and Carbon Copy (CC) recipients
    ' and store them in a variabel
    
    For i = 0 To Recipients.Count - 1
        If i = Recipients.Count - 1 Then
            separator = ""
        End If
    
        Set re = Recipients.item(i)
        If re.ReType = 0 Then
            ReTo = ReTo & re.Name & "&nbsp;(<a href=""mailto:"& re.EMail &""">" & re.EMail & "</a>)" & separator
        else
            ReCC = ReTo & re.Name & "&nbsp;(<a href=""mailto:"& re.EMail &""">" & re.EMail & "</a>)" & separator
        End If
    Next
    
    ' This function iterates through the Attachments object,
    ' and saves the attachment to the server's disk.
    ' It also returns a nicely formatted string with a
    ' link to the attachment.
    Function getAttachments()
          Set Attachments = msg.Attachments
          separator = ", "
    
          For i = 0 To Attachments.Count - 1
            If i = Attachments.Count - 1 Then
                separator = ""
             End If
    
             Set at = Attachments(i)
             at.SaveToFile( "c:\EMail\attachments\" & at.Name )
             getAttachments = getAttachments & "<a href=""/EMail/attachments/" & at.Name &""">" &_
                                 at.Name & "(" & at.Size  & " bytes)" & "</a>" & separator
          Next
    End Function
      
    %>    
    <html>
      <body>
        <TABLE>
          <tr>
            <td>Subject</td>
            <td><%= msg.Subject %></td>
          </tr>
          <tr>
            <td>From</td>
            <td><%= msg.FromName %></td>
          </tr>
          <tr>
            <td>Recipients To</td>
            <td><%= ReTO %></td>
          </tr>
          <tr>
            <td>Recipients CC</td>
            <td><%= ReCC %></td>
          </tr>
          <tr>
            <td>Attachments</td>
            <td><%= getAttachments %></td>
          </tr>
          <tr>
            <td>Body</td>
            <td><pre><%= msg.Body %></pre></td>
          </tr>        
        </TABLE>
      </body>
    </html>
    <%

  end if

  pop3.Disconnect

%>


<%

'*************************************************
'*                                               *
'*   Produced by Dimac                           *
'*                                               *
'*   More examples can be found at                  *
'*   http://tech.dimac.net                       *
'*                                               *
'*   Support is available at our helpdesk        *
'*   http://support.dimac.net                    *
'*                                               *
'*   Our main website is located at              *
'*   http://www.dimac.net                        *
'*                                               *
'*************************************************

  set JMail = Server.CreateObject( "JMail.Speedmailer" )

    ' Send a simple email in a single method call.
    ' You can add multiple recipients by separating them with a ","

  JMail.SendMail "me@myDomain.com", "to@otherDomain.com, to2@otherDomain.com", "subject", "Body", "mail.dimac.net"


%>
<html>
Mail sent..
</html>


一个新的JMail(4.3版本)发送代码 
该段代码涉及到JMail v4.3的大部分常用方法。
包括邮件基本信息、身份验证、附件等。无需很多的修改就可以使用,也可以改成函数或过程。
<%
Dim JMail, contentId
Set JMail = Server.CreateObject("JMail.Message") 

JMail.Charset = "gb2312" ' 邮件字符集,默认为"US-ASCII"
' JMail.ISOEncodeHeaders = False ' 是否进行ISO编码,默认为True

' 发送者信息(可用变量方式赋值)
JMail.From = "user@2mysite.net" ' 发送者地址
JMail.FromName = "D.J." ' 发送者姓名
JMail.Subject = "mailsubject" ' 邮件主题

' 身份验证
JMail.MailServerUserName = "user" ' 身份验证的用户名
JMail.MailServerPassword = "password" ' 身份验证的密码

' 设置优先级,范围从1到5,越大的优先级越高,3为普通
JMail.Priority = 3

JMail.AddHeader "Originating-IP", Request.ServerVariables("REMOTE_ADDR")

' 加入一个收件人【变量email:收件人地址】可以同一语句重复加入多个
JMail.AddRecipient(email)

' 加入附件【变量filename:附件文件的绝对地址,确保用户IUSR_????有访问的权限】
' 【参数设置是(True)否(False)为Inline方式】
contentId = JMail.AddAttachment (filename, True)

' 邮件主体(HTML(注意信件内链接附件的方式))
JMail.HTMLBody = "<html><head><META content=zh-cn http-equiv=Content-Language><meta http-equiv=""Content-Type"" content=""text/html; charset=gb2312""><style type=text/css>A:link { FONT-SIZE: 9pt; TEXT-DECORATION: none; color: #000000}A:visited {FONT-SIZE: 9pt; TEXT-DECORATION: none; color: #666666}A:hover {COLOR: #ff6600; FONT-SIZE: 9pt; TEXT-DECORATION: underline}BODY {FONT-SIZE: 9pt} --></style></head><body bgcolor=""#FFFFFF"" text=""#666666"" leftmargin=""0"" topmargin=""30"" link=""#FF9900""><center>点击这里<a href=' cid:" & contentId & "' >[附件文件]</a>将文件保存</center></body></html>"

' 邮件主体(文本部分)
JMail.Body = "我们的邮件采用了HTML格式,但是您的邮件查看软件可能不支持。您可以访问以下地址来查看:http://music.liuxuan.com"

' 发送【调用格式:objJMail.Send([username:password@]SMTPServerAddress[:Port])】
JMail.Send("user:password@smtp.21cn.com")

' 关闭并清除对象
JMail.Close()
Set JMail = Nothing
%>


One of the most common uses for Dimac w3 JMail is when a form is filled out by the user and then emailed by ASP. This example shows you just how easy it is.
 
First of all we need a form which posts to our JMail page. 
   JmailForm.asp
<html>
<head>
<title>emailform</title>
</head>
<body>
<form method="post" action="SendMail.asp">
   Complete this form and click the submit-button. We will answer your
   questions as soon as possible.
   <br><br>
   Your name<br>
   <input type="text" size="25" name="name"><br>
  
   Your email<br>
   <input type="text" size="25" name="email"><br>   Recipient email<br>
   <input type="text" size="25" name="recipient"><br> State your business<br>
   <select name="subject" size="1">
    <option value="help">help
       <option value="tips">tips
       <option value="other">other
   </select>
   <br> Enter your question<br>
   <textarea name="body" cols="40" rows="15" wrap="PHYSICAL"></textarea>
   <br>
   <input type="submit" value="  Submit ">
</form>
</body>
</html>
  
Then we need to catch the post and read the form. Pick up all information and create the e-mail.

   SendMail.asp
<%@LANGUAGE = VBSCRIPT%> <html>
<body>

<%
' Get the form data
name        = Request.Form("name")
senderEmail = Request.Form("email")
subject    = "Regarding " & Request.Form("subject")
recipient   = Request.Form("recipient")
body        = Request.Form("body")

' Create the JMail message Object
set msg = Server.CreateOBject( "JMail.Message" )

' Set logging to true to ease any potential debugging
' And set silent to true as we wish to handle our errors ourself
msg.Logging = true
msg.silent = true

' Enter the sender data
msg.From = senderEmail
msg.FromName = name

' Note that as addRecipient is method and not
' a property, we do not use an equals ( = ) sign
msg.AddRecipient recipient

' The subject of the message
msg.Subject = subject

' And the body
msg.body = body

' Now send the message, using the indicated mailserver
if not msg.Send("mail.myDomain.net" ) then
    Response.write "<pre>" & msg.log & "</pre>"
else
    Response.write "Message sent succesfully!"
end if
' And we're done! the message has been sent.
%>
</body>
</html>

(以上代码可以写成函数调用)
'*************************************************************
' 目的:
' 参数:
'    UserName    SMTP用户名
'    Password    SMTP用户密码
'    mailFrom    发件人邮箱
'    fromName    发件人名称
'    Recipient    收件人
'    mSubject    邮件主题
'    mBody        邮件内容
'    SMTPServer    SMTP服务器
'*************************************************************
Sub sendMail(UserName,Password,mailFrom,fromName,Recipient,mSubject,mBody,SMTPServer)
    ' 创建对象
    Set objMsg = Server.CreateOBject( "JMail.Message" )

    ' 设置成调试模式
    objMsg.Logging = true
    objMsg.silent = true

    '设置SMTP帐号用户与密码
    objmsg.MailServerUserName = UserName
    objMsg.MailServerPassWord = Password

    ' 设置发件人信息
    objMsg.From = mailFrom
    objMsg.FromName = fromName

    ' 设置收件人
    objMsg.AddRecipient Recipient

    ' 邮件主题
    objMsg.Subject = mSubject

    ' 邮件内容
    objMsg.Body = mBody

    ' 使用指定SMTP服务器发送
    If Not objMsg.Send(SMTPServer) Then
        Response.write "<pre>" & objMsg.Log & "</pre>"
    Else
        Response.write "Message sent succesfully!"
    End If
    
End Sub

'******************************************************************************
' 目的:使用JMAIL利用要求身份验证的SMTP发邮件
' 参数:
'        UserName
'        Password
'        SMTPServer
'        mSubject
'        mBody,Sender
'        mFromName
' 返回值:none
'******************************************************************************
Sub sendMail(UserName,Password,SMTPServer,mSubject,mBody,Sender,mFromName)
    On Error Resume Next
    Set objJmail = Server.CreateObject("Jmail.Message")
    '调试设置
    objJmail.Logging = true
    objJmail.Silent = true
    
    'SMTP帐号设置
    objJmail.MailServerUserName = UserName
    objJmail.MailServerPassWord = Password

    objJmail.AddRecipient UserName
    objJmail.From = UserName    '
    objJmail.FromName = mFromName
    objJmail.ReplyTo = mSender

    objJmail.Subject = mSubject    '
    objJmail.Body = mBody    '

    objJmail.Send( SMTPServer )
    
    If err.number <> 0 Then
        Response.Write "邮件发送出现错误,具体信息如下:<br>" & Replace(objJmail.Log,Chr(13),"<br>")
    Else
        Response.Write "邮件成功发送!"
    End If

End Sub

用存储过程实现ASP对数据库访问

一、ADO概述
ActiveX 数据对象 (ADO) 是一种既易于使用又可扩充的技术,用来将数据库访问添加到您的 Web 页可以使用 ADO 编写简洁和可升级的脚本以连接到与 OLE DB 兼容的数据源,如数据库、电子表格、顺序数据文件或电子邮件目录。OLE DB 是一个系统级的编程接口,它提供一套标准的 COM 接口,用来展示数据库管理系统的功能。使用 ADO 的对象模型,您可以轻松地(使用 VBScript 或 JScript 等脚本语言)访问这些接口并将数据库功能添加到您的 Web 应用程序中。另外,您还可以使用 ADO 访问与开放式数据库互连 (ODBC) 兼容的数据库。
如果您是一位对数据库互连知识有一定了解的脚本编写者,您将会发现 ADO 的命令语法很简单,而且很容易使用。如果您是一位经验丰富的开发人员,您将会非常欣赏 ADO 提供的这种可升级的对各种数据源的高性能访问。 继续阅读