`
javatoyou
  • 浏览: 1016578 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

ASP.net 2.0发送邮件实例,本人已经测试通过,贴出代码

 
阅读更多

  今天小试了一下ASP.net 2.0中System.Net.Mail发送电子邮件。

  开始的几次尝试都不成功,出现超时和返回错误消息等情况,原来是邮箱不支持SMTP发送。

  后来几经波折,我找到了新浪的邮箱,发现新浪邮箱支持SMTP发送电子邮件,因为测试下面代码发现在收件箱里已经收到邮件。现在我把代码贴出来,供还没研究过System.Net.Mail发送邮件的朋友参考,代码如下:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class manage_mail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MailAddress MessageFrom = new MailAddress("username@sina.com"); //发件人邮箱地址
string MessageTo = "username@datdns.com"; //收件人邮箱地址
string MessageSubject = "邮件主题"; //邮件主题
string MessageBody = "这里是邮件内容。"; //邮件内容
if (Send(MessageFrom, MessageTo, MessageSubject, MessageBody))
{
Response.Write("发送邮件成功");
}
else
{
Response.Write("发送邮件失败");
}
}
/// <summary>
/// 发送电子邮件
/// </summary>
/// <param name="MessageFrom">发件人邮箱地址</param>
/// <param name="MessageTo">收件人邮箱地址</param>
/// <param name="MessageSubject">邮件主题</param>
/// <param name="MessageBody">邮件内容</param>
/// <returns></returns>
public bool Send(MailAddress MessageFrom, string MessageTo, string MessageSubject, string MessageBody)
{
MailMessage message = new MailMessage();

message.From = MessageFrom;
message.To.Add(MessageTo); //收件人邮箱地址可以是多个以实现群发
message.Subject = MessageSubject;
message.Body = MessageBody;
message.IsBodyHtml = true; //是否为html格式
message.Priority = MailPriority.High; //发送邮件的优先等级

SmtpClient sc = new SmtpClient();
sc.Host = "smtp.sina.com"; //指定发送邮件的服务器地址或IP
sc.Port = 25; //指定发送邮件端口
sc.Credentials = new System.Net.NetworkCredential("username@sina.com", "password"); //指定登录服务器的用户名和密码
try
{
sc.Send(message); //发送邮件
}
catch
{
return false;
}
return true;
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics