.NET 中收发邮件有一个命名空间叫做 system.Net.Mail
用了这个里面的mailMessage类我们就可以将我们日常邮件的属性与之对应起来。
例如:
MailMessage mailMessage = new MailMessage();
mailMessage.From="sanba@qq.com"
同理里面也有 to cc bcc等方法,详细请看全面的msdn:
以下是我的一个小小的例子,通过我的hotmail邮箱,向我的qq邮箱发送邮件。
asp.net的。
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
From:
<p><asp:TextBox ID="txtFromAddress" runat="server" Columns="35"></asp:TextBox></p>
<p>To:</p>
<p><asp:TextBox ID="txtToAddres" runat="server" Columns="35">***@qq.com</asp:TextBox></p>
<p>Subject:</p>
<p><asp:TextBox ID="txtSubject" runat="server" Columns="50">Test email</asp:TextBox></p>
<p>Body:</p>
<p><asp:TextBox ID="txtBody" runat="server" Columns="256" TextMode="MultiLine" Rows="6">Test mail blah blah~</asp:TextBox></p>
</div>
<asp:Button ID="btnSend" runat="server" οnclick="btnSend_Click"
Text="SendMail" />
</form>
</body>
</html>
CS:
protected void btnSend_Click(object sender, EventArgs e)
{
MailMessage mailMessage = new MailMessage();
//mailMessage.From = new MailAddress(txtFromAddress.Text.Trim());
mailMessage.From = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["fromEmailAddres"]);
mailMessage.To.Add(new MailAddress(txtToAddres.Text.Trim()));
mailMessage.Subject = txtSubject.Text.Trim();
mailMessage.Body = txtBody.Text.Trim();
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
//smtpClient.Host = "smtp.live.com";
//smtpClient.Port = 25;
//smtpClient.Credentials=new System.Net.NetworkCredential("***@hotmail.com","***");
try
{
smtpClient.Send(mailMessage);
Response.Write("success");
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="fromEmailAddres" value="***@hotmail.com"/>
</appSettings>
<system.net>
<!--<defaultProxy>
<proxy
usesystemdefault="False"
proxyaddress="http://itgproxy.***.com:80"
bypassonlocal="True"></proxy>
</defaultProxy>-->
<mailSettings>
<smtp from="heyrdaxm@hotmail.com">
<!--<network host="pop3.live.com" defaultCredentials="false" port="995" userName ="***账号" password="***密码"></network>-->
<network host="smtp.live.com" defaultCredentials="false" port="25" userName ="***@hotmail.com" password="***"></network>
</smtp>
</mailSettings>
</system.net>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
</configuration>
账号密码等用***代替了。
这是一个很简单的程序。
有两种输入账号密码的方法。
1.用SmtpClient中的Credentials属性。(见注释部分)
2.在web.config中配置。
然后如果你上网用到了代理可以添加代理配置。(在web.config中)。
各个网站的smtp服务器需要百度查一下,这里就不介绍了。
希望能帮助到有需要的朋友。