1、新建项目
-- 选择Visual C# - 类库
-- 项目名称:如 SendMailLib
-- 去掉选中项 ”为解决方案创建目录”
-- 修改文件名Class1.cs 为 SendMail.cs (类名称自动更改为 SendMail)
2、修改项目 - 属性
-- 应用程序
目录框架不限制,只要服务器能提供相应的Net版本
-- 生成
配置选择:Release
输出选中:“为COM互操作注册”
-- 签名
SN命令参考目录:C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools
命令行:sn -k SendMailKey.snk
在当前目录生成snk文件,将该文件copy到项目根目录
选中 ”为程序集签名“,浏览,选择项目文件下的.snk文件
3、 修改 Properties - AssemblyInfo.cs
false 改为 true
[assembly: ComVisible(true)]
4、 编写代码,win7及以上版本,以管理员方式运行,否则在编译时可能提示没有权限
-- Demo --
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace SendMailLib
{
[ComVisible(true)]
[Guid("FAF8401B-8AE4-4161-911C-E800BD50AA40")]
public interface ISendMail
{
void Initialize();
string MailServer { get; set; } //可读写属性
int Port { get; set; }
string Send();
void Dispose();
}
[ComVisible(true)]
[Guid("DE8F5369-C004-4679-985E-F5F37272947D")]
public class SendMail:ISendMail
{
private string _mailServer;
private int _port = 25;
public void Initialize()
{
//throw new NotImplementedException();
}
public string MailServer
{
get
{
return _mailServer;
}
set
{
_mailServer = value;
}
}
public int Port
{
get
{
return _port;
}
set
{
_port = value;
}
}
public string Send()
{
try
{
return "Send";
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
return ex.Message;
}
}
public void Dispose()
{
}
}
}
5、添加程序集到全局缓存,以便于在任意位置注册该dll组件
copy SendMail.dll 到 gacutil命令相同的目录
(命令参考目录 C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools,gacutil运行环境版本不限,示例使用NETFX 4.5.1)
执行:gacutil /i SendMailLib.dll
6、注册组件及类型到注册表
命令行转到regasm对应的目录,这里不需要指定SendMailLib.dll位置,自动从全局缓存获取,
命令参考目录:C:\Windows\Microsoft.NET\Framework64\v4.0.30319 </div><div> (注意:版本必须根据操作系统选择 x86 / 64bit, 否则注册后无法调用)
执行:
regasm SendMailLib.dll
7、注销组件,并清除相应缓存
regasm SendMailLib.dll /unregister
pause gacutil /u SendMailLib
8、在ASP中调用
dim sm
set sm = Server.CreateObject("SendMailLib.SendMail")
sm.Initialize
sm.MailServer = "localhost"
sm.Port = 25
response.Write(sm.MailServer & ":" & sm.Port)
sm.Dispose
set sm =nothing
9、在PHP中调用
需要
[PHP_COM_DOTNET]
extension=php_com_dotnet.dll)
$sm = new COM("SendMailLib.SendMail");
echo $sm->Send();