[源码下载]


在asp.net 2.0中发送邮件


1、在web.config中的<configuration>内加入如下配置信息(host—smtp服务地址;port—端口号;userName—用户名;password—密码。请自行修改)。
  <system.net>
    
<mailSettings>

      
<smtp>
        
<network host="smtpserver" port="25" userName="uid" password="pwd" />
      
</smtp>

    
</mailSettings>
  
</system.net>

2、aspx页面HTML代码
    <table border="0">
        
<tr>
            
<td>
                发件人
            
</td>
            
<td>
                
<asp:TextBox runat="server" ID="emailfrom"></asp:TextBox>
            
</td>
        
</tr>
        
<tr>
            
<td>
                收件人
            
</td>
            
<td>
                
<asp:TextBox runat="server" ID="emailto"></asp:TextBox>
            
</td>
        
</tr>
        
<tr>
            
<td>
                主题
            
</td>
            
<td>
                
<asp:TextBox runat="server" ID="subject"></asp:TextBox>
            
</td>
        
</tr>
        
<tr>
            
<td>
                附件
            
</td>
            
<td>
                
<asp:FileUpload ID="attachment" runat="server" />
            
</td>
        
</tr>
        
<tr>
            
<td>
                内容
            
</td>
            
<td>
                
<asp:TextBox runat="server" ID="body" TextMode="MultiLine" Columns="50" Rows="10"></asp:TextBox>
            
</td>
        
</tr>
        
<tr>
            
<td colspan="2" align="center">
                
<asp:Button runat="server" ID="btnSend" Text="发送" OnClick="btnSend_Click" />
            
</td>
        
</tr>
    
</table>

3、实例化一个MailMessage并设置其属性
        MailMessage mm = new MailMessage(emailfrom.Text, emailto.Text);

        mm.Subject 
= subject.Text;
        mm.Body 
= body.Text;
        
// HTML格式
        mm.IsBodyHtml = true;

        
// 添加附件
        mm.Attachments.Add(new Attachment(attachment.PostedFile.InputStream, attachment.FileName));

        
/*其他如抄送、优先级之类的都可以在MailMessage类的属性中设置*/

4、实例化一个SmtpClient,调用其Send方法,参数为MailMessage对象
        SmtpClient sc = new SmtpClient();

        
// smtp编码设置(不用web.config)
        
// sc.Host = "";
        
// sc.Port = 25;
        
// sc.Credentials = new NetworkCredential("username", "password");

        
try
        
{
            sc.Send(mm);
            Response.Write(
"ok");
        }

        
catch (Exception ex)
        
{
            
// 与smtp相关的错误
            if (ex is SmtpException)
            
{
                
// ex.ToString();
                Response.Write("smtp发信失败");
            }

            
else
            
{
                Response.Write(ex.ToString());
            }

        }


OK
[源码下载]


webabcd 2007-01-03 18:38 发表评论

文章来源:http://www.cnblogs.com/webabcd/archive/2007/01/03/610735.html