首页 > 数据库 > SQL Server > 正文

SQL Server中发送邮件的新方式

2024-08-31 00:48:16
字体:
来源:转载
供稿:网友
  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。

  • 说是新方式,其实也是早就用到的技术了,所以放上来!

    在.net中,大家知道,可以使用system.web.mail来发送邮件。在framework 1.1下支持验证。

    private void page_load(object sender, system.eventargs e)
    {
           mailmessage mail = new mailmessage();
           mail.to = "[email protected]";
           mail.from = "[email protected]";
           mail.subject = "this is a test email.";
           mail.body = "some text goes here";
           mail.fields.add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
           mail.fields.add("http://schemas.microsoft.com/cdo/configuration/sendusername", "my_username_here"); //set your username here
          mail.fields.add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "super_secret"); //set your password here

        smtpmail.smtpserver = "mail.mycompany.com";  //your real server goes here
        smtpmail.send( mail );
    }

    以前我曾写过在.net下发送邮件的方法,详见:

    http://dev.csdn.net/develop/article/17/17189.shtm

     

    sql server中,我们一般使用sql本身的邮件发送方式,但需要配置exchage server、outlook等,也是一个比较繁琐的事情。很多人抱怨说配置不成功。

    其实,我们可以在 sql server中创建 ole 对象实例,调用iis smtp自带的发送组件来实现邮件发送。

    我们建立这个存储过程,你需要修改的地方是,smtpserver的名字

    create procedure sys_sendmail @from varchar(100) , @to varchar(100) , @bcc varchar(500), @subject varchar(400)=" ", @body ntext =" "

    as

    declare @object int
    declare @hr int

    exec @hr = sp_oacreate 'cdo.message', @object out

    exec @hr = sp_oasetproperty @object, 'configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").value','2'
    exec @hr = sp_oasetproperty @object, 'configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").value', 'smtp.163.com'

    --下面三条语句是smtp验证,如果服务器需要验证,则必须要这三句,你需要修改用户名和密码
    exec @hr = sp_oasetproperty @object, 'configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate").value','1'
    exec @hr = sp_oasetproperty @object, 'configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusername").value','lihonggen0'
    exec @hr = sp_oasetproperty @object, 'configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendpassword").value','xxx'

    exec @hr = sp_oamethod @object, 'configuration.fields.update', null
    exec @hr = sp_oasetproperty @object, 'to', @to
    exec @hr = sp_oasetproperty @object, 'bcc', @bcc
    exec @hr = sp_oasetproperty @object, 'from', @from
    exec @hr = sp_oasetproperty @object, 'subject', @subject

    exec @hr = sp_oasetproperty @object, 'textbody', @body
    exec @hr = sp_oamethod @object, 'send', null

    --判断出错
    if @hr <> 0
    begin
       exec sp_oageterrorinfo @object  
       return @object
    end
    print 'success'
    exec @hr = sp_oadestroy @object

    go

    注意:必须确保安装smtp,可以访问cdo对象。
    发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表