asp.net使用smtp协议实现简单的发送邮件(支持附件)

引入下面两个名称空间

using System.Net.Mail;

using System.Net;

前台页面代码

<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
    <title></title>
</head>
<body>
    <formid="form1"runat="server">
    <div>
     
        发送人:<asp:TextBoxID="txtFrom"runat="server"></asp:TextBox>
        <br/>
        收件人:<asp:TextBoxID="txtTo"runat="server"></asp:TextBox>
        <br/>
        主题:<asp:TextBoxID="txtTheme"runat="server"></asp:TextBox>
        <br/>
        附件:<asp:FileUploadID="fpAttachment"
            runat="server"/>
        <br/>
        内容:<asp:TextBoxID="txtContent"runat="server"Rows="20"TextMode="MultiLine"
            Width="300px"></asp:TextBox>
        <br/>
        <asp:ButtonID="Button1"runat="server"Text="发送"οnclick="Button1_Click"/>
    </div>
    </form>
</body>

</html>

================================================================================
后台C#代码:
 protected void Button1_Click(objectsender, EventArgs e)
    {
        //测试通过,能发送带有附件的邮件
        stringfrom = txtFrom.Text.Trim(); //发件人
        stringto = txtTo.Text.Trim();//收件人
        stringtheme = txtTheme.Text.Trim();//主题
        //string file = fpAttachment.FileName;//附件文件名
        stringfile =fpAttachment.PostedFile.FileName;//附件文件路径(包含文件名)
        stringcontent = txtContent.Text; //邮件内容
        MailMessage messge = newMailMessage(from,to);  //邮件消息实例
        messge.Body = content; 
        messge.Subject = theme;
        messge.IsBodyHtml = true;
        messge.Priority = MailPriority.High;//邮件优先级别
        messge.Attachments.Add(newAttachment(file));
        SmtpClient client = newSmtpClient(); //Smtp协议
        client.Host = "smtp.163.com"; //发送人的Smtp主机名称或IP地址,实例为163邮箱的Smtp地址
        client.Credentials = newNetworkCredential("cpeng0907@163.com", "发送邮箱的密码");//验证发件人的身份凭据
        client.Send(messge);
        messge.Attachments.Dispose();
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值