其实在2005中发送邮件很容易,只不过在调用邮件服务器时可能要用到身份验证,而在2003下是用
System.Web.Mail;
空间下的System.Web.Mail.MailMessage实例,
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername","
用户名"
);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword","
密码"
);
其中mail为System.Web.Mail.MailMessage的实例。而在2005下已经建议用System.Net.Mail;而System.Net.Mail.MailMessage实例没有Fields属性,所以要用新的验证方法。
2005
中的邮件服务器身份验证其实更容易,只要在WebConfig中进行简单配置即可,如:
<configuration>
<system.net>
<mailSettings>
<smtp from="
用户名@163.com">
<network host="smtp.163.com" userName="
用户名" password="密码" port="25" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
后台代码举例:
using System.Net.Mail;
protected void btn_send_Click(object sender, EventArgs e)
{
try
{
MailAddress from = new MailAddress("
发件人地址");//如test@163.com,初步测试,用test@sina.com不行,不知是不是用163的邮件服务器,就必须用163邮箱的用户名
MailAddress to = new MailAddress("
收件人地址");//如test@tom.com
MailMessage mail = new MailMessage(from, to);
mail.Subject = "
主题";
mail.Body = "
正文";
//
以下设置服务器
SmtpClient mySmth = new SmtpClient();
//
以下为增加附件
Attachment data = new Attachment("
附件路径"
);
mail.Attachments.Add(data);
mySmth.Send(mail);
mail.Dispose();
}
catch
{
Response.Write("<script>alert('
邮件发送出错!')</script>");
}
}