.net发送邮件代码示例
下面的代理已经调试过,用的是163的SMTP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;
using System.Net;
namespace Test.Email
{
public partial class TestEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void btnSendEmail_Click(object sender, EventArgs e)
{
MailAddress MessageFrom = new MailAddress("XXXX@163.com"); //发件人邮箱地址
string MessageTo = xx@xx.com; //收件人邮箱地址
string MessageSubject = "测试邮件发送"; //邮件主题
string MessageBody = "如果你收到消息,那我的邮件就测试成功了,大功告成!"; //邮件内容
try
{
Send(MessageFrom, MessageTo, MessageSubject, MessageBody);
Response.Write("发送邮件成功");
}
catch (Exception ex)
{
Response.Write("发送邮件失败" + ex.Message);
}
}
/// <summary>
/// 发送电子邮件
/// </summary>
/// <param name="MessageFrom">发件人邮箱地址</param>
/// <param name="MessageTo">收件人邮箱地址</param>
/// <param name="MessageSubject">邮件主题</param>
/// <param name="MessageBody">邮件内容</param>
public void Send(MailAddress MessageFrom, string MessageTo, string MessageSubject, string MessageBody)
{
MailMessage message = new MailMessage();
message.From = MessageFrom;
string[] ss = MessageTo.Split(';');
foreach (string s in ss)
message.To.Add(s); //收件人邮箱地址可以是多个以实现群发
message.Subject = MessageSubject;
message.Body = MessageBody;
message.IsBodyHtml = true; //是否为html格式
message.Priority = MailPriority.High; //发送邮件的优先等级
message.SubjectEncoding = Encoding.Default;
message.BodyEncoding = Encoding.Default;
SmtpClient sc = new SmtpClient();
sc.Host = "smtp.163.com"; //指定发送邮件的服务器地址或IP
sc.Port = 25; //指定发送邮件端口
sc.Credentials = new System.Net.NetworkCredential("用户名", "密码"); //指定登录服务器的用户名(不带后缀)和密码
try
{
sc.Send(message); //发送邮件
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}